Question

In: Computer Science

JAVA How to make a graph class that uses a linked list class to store nodes...

JAVA

How to make a graph class that uses a linked list class to store nodes and linked list within each node to store adjacency list

The linked list class has been made already.  

import java.util.*;


public class LinkedList implements Iterable
{
private int size = 0;
private Node head;
private Node tail;


private class Node
{
private T data;
private Node prev;
private Node next;

public Node(T data)
{
this.data = data;

}

}

  
public Iterator iterator()
{
return new LinkedListIterator(this);
}

  
private class LinkedListIterator implements Iterator
{
private Node iterNext;

public LinkedListIterator(LinkedList theList)
{
iterNext = theList.head;
}

public boolean hasNext()
{
return (iterNext != null);
}

public T next()
{
T value;
  
if (iterNext == null)
{
  
value = null;
}
else
{
value = iterNext.data;
iterNext = iterNext.next;
}
  
return value;
}

public void remove()
{
throw new UnsupportedOperationException("Not supported");
}
}


public void insertFirst(T value)
{

Node nodeVal = new Node(value);

if(isEmpty())
{
nodeVal.next = null;
nodeVal.prev = null;
head = nodeVal;
tail = nodeVal;
size++;
}
else
{
nodeVal.next = head;
nodeVal.prev = null;
head.prev = nodeVal;
head = nodeVal;
size++;
}
}

public void insertLast(T value)
{

Node nodeVal = new Node(value);

if (isEmpty())
{
nodeVal.next = null;
nodeVal.prev = null;
head = nodeVal;
tail = nodeVal;
size++;
}
else
{
tail.next = nodeVal;
nodeVal.next = null;
nodeVal.prev = tail;
tail = nodeVal;
size++;
}
}


public int size()
{

return size;

}

public boolean isEmpty()
{
return size() == 0;
}

public Node deleteFirst()
{

Node returnVal;

if (isEmpty())
{
throw new RuntimeException("Empty list");   
}
else
{

Node temp = head;
returnVal = head;
head = temp.next;
head.prev = null;
size--;
}

return returnVal;
}

public Node deleteLast()
{

Node returnVal;
  
if (isEmpty())
{
throw new RuntimeException("Empty list");
}
else
{
Node temp = tail;
returnVal = tail;
tail = temp.prev;
tail.next = null;
size--;
}

return returnVal;
}


public Object peekFirst()
{
if (isEmpty())
{
throw new IllegalArgumentException("Empty list");
}

return head.data;
}

public Object peekLast()
{
if (isEmpty())
{
throw new IllegalArgumentException("Empty list");
}
  
return tail.data;
}


public void printNodes(LinkedList list)
{

Iterator itr = list.iterator();

System.out.println("Here is the current list");
  
if(isEmpty())
{
System.out.println("The list is empty\n");
}
else
{
while(itr.hasNext())
{
T o = (T)(itr.next());
System.out.print(o + " ");
}
}

}

}

  

IMPORTANT! The graph class must include these class fields;

vertices, edges (of type LinkedList)

and must include these methods;

a constructor, insertVertex, insertEdge, hasVertex, getVertexCount, getEdgeCount, getVertex, getEdge, getAdjacent, getAdjacentE

Solutions

Expert Solution

The code is explained in the inline comments.

Graphs used to test:

Screenshot:

Graph.java:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class Graph<T> {

   HashMap< T , LinkedList<T>> graph;
  
   public Graph() {
       graph = new HashMap<T , LinkedList<T>>();
   }
  
   /**
   * The below method is used to add the edge in the graph
   * @param graph
   * @param src
   * @param dest
   */
   public void addEdge(HashMap<T , LinkedList<T>> graph , T src , T dest) {
       if(graph.containsKey(src)){
           // if graph already has the source node
           graph.get(src).insertLast(dest);
       }else {
           // if graph doesn't have source node
           LinkedList<T> res = new LinkedList<T>();
           res.insertFirst(dest);
           graph.put(src,res);
       }
   }
   public static void main(String[] args) {
      
       // we implement graph in adjacency list format
      
       // for testing I'm using the graph with integers
      
       Graph<Integer> g =new Graph<Integer>();
      
       // for undirected graph in both directions
       g.addEdge(g.graph, 71 , 52);
       g.addEdge(g.graph, 52, 71);

       g.addEdge(g.graph, 71 , 85);
       g.addEdge(g.graph, 85, 71);

       g.addEdge(g.graph, 85, 52);
       g.addEdge(g.graph, 52, 85);
       g.addEdge(g.graph, 64, 85);
       g.addEdge(g.graph, 85, 64);
       g.addEdge(g.graph, 85, 96);
       g.addEdge(g.graph, 96, 85);

       g.addEdge(g.graph, 52, 64);
       g.addEdge(g.graph, 64, 52);
       g.addEdge(g.graph, 52, 93);
       g.addEdge(g.graph, 93, 52);

       g.addEdge(g.graph, 93, 64);
       g.addEdge(g.graph, 64, 93);
       g.addEdge(g.graph, 96, 64);
       g.addEdge(g.graph, 64, 96);
      
       g.addEdge(g.graph, 96, 93);
       g.addEdge(g.graph, 93, 96);
      
  
// for directed graph we need to use only 1 edges
/*
       g.addEdge(g.graph, 71 , 52);
      
*/
g.printGraphInAdjacencyList();
   }

   /**
   * The below method is used to get the string format of object for all the destinations from the node
   * @param list
   * @return
   */
   public String getNodesAsStr(LinkedList<T> list) {

       Iterator itr = list.iterator();
       String res = "";

           while (itr.hasNext()) {
               T o = (T) (itr.next());
               if(res!="") {
                   res = res +" -> "+o;  
               }else {res += o;}
              
           }
       return res;

   }
   /**
   * The below method is used to represent the graph
   */
   public void printGraphInAdjacencyList() {
      
       Iterator<Entry<T, LinkedList<T>>> keys = graph.entrySet().iterator();
       while (keys.hasNext()) {
       Map.Entry pair = (Map.Entry)keys.next();
      
       LinkedList<T> res = (LinkedList<T>) pair.getValue();
       System.out.println(pair.getKey() + " => " +getNodesAsStr(res));
      
       }
   }
}


Related Solutions

How to read a text file and store the elements into a linked list in java?...
How to read a text file and store the elements into a linked list in java? Example of a text file: CS100, Intro to CS, John Smith, 37, 100.00 CS200, Java Programming, Susan Smith, 35, 200.00 CS300, Data Structures, Ahmed Suad, 41, 150.50 CS400, Analysis of Algorithms, Yapsiong Chen, 70, 220.50 and print them out in this format: Course: CS100 Title: Intro to CS Author: Name = John Smith, Age = 37 Price: 100.0. And also to print out the...
Create a generic Linked List that does NOT use the Java library linked list. Make sure...
Create a generic Linked List that does NOT use the Java library linked list. Make sure it contains or access a subclass named Node (also Generic). And has the methods: addFirst(), addLast(), add(), removeFirst(), removeLast() and getHead(). In a separate Java class provide a main that creates an instance of your LinkedList class that creates an instance of your LinkedList that contains String types. Add the five names (you pick them) to the list and then iterate through the list...
Given a linked list of integers, remove any nodes from the linked list that have values...
Given a linked list of integers, remove any nodes from the linked list that have values that have previously occurred in the linked list. Your function should return a reference to the head of the updated linked list. (In Python)
Java the goal is to create a list class that uses an array to implement the...
Java the goal is to create a list class that uses an array to implement the interface below. I'm having trouble figuring out the remove(T element) and set(int index, T element). I haven't added any custom methods other than a simple expand method that doubles the size by 2. I would prefer it if you did not use any other custom methods. Please use Java Generics, Thank you. import java.util.*; /** * Interface for an Iterable, Indexed, Unsorted List ADT....
Can you make this singular linked list to doubly linked list Create a Doubly Linked List....
Can you make this singular linked list to doubly linked list Create a Doubly Linked List. Use this to create a Sorted Linked List, Use this to create a prioritized list by use. Bring to front those links recently queried. -----link.h------ #ifndef LINK_H #define LINK_H struct Link{ int data; Link *lnkNxt; }; #endif /* LINK_H */ ----main.cpp---- //System Level Libraries #include <iostream> //I/O Library using namespace std; //Libraries compiled under std #include"Link.h" //Global Constants - Science/Math Related //Conversions, Higher Dimensions...
how do you add two matrices linked list in java? (am using linked list because 2D...
how do you add two matrices linked list in java? (am using linked list because 2D arrays are not allowed.) ex [1st matrix] 1 3 2 4 2 1 3 2 4 + [2nd matrix] 3 2 3 2 1 4 5 2 3 = [3rd matrix] 4 5 5 6 3 5 8 4 7
1.Please write a C++ program that counts the nodes in a linked list with the first...
1.Please write a C++ program that counts the nodes in a linked list with the first node pointed to by first. Also please explain. 2. Write a program to determine the average of a linked list of real numbers with the first node pointed to by first. 3. Determine the computing times of the algorithms in question 1 and 4. Write a program to insert a new node into a linked list with the first node pointed to by first...
1. Considering singly linked list, be able to determine if inserting nodes at the end of...
1. Considering singly linked list, be able to determine if inserting nodes at the end of a LinkedList is less time-efficient than inserting them at the front of the list. 2. Be able to differentiate between the data structures Stack, Queue, and Linked List. 3. Determine between the acronyms LIFO and FIFO, and be able to give one real life example where each is applicable
Data Structures on Java Basic Linked List exercises a. Suppose x is a linked-list node and...
Data Structures on Java Basic Linked List exercises a. Suppose x is a linked-list node and not the last node on the list. What is the effect of the following code fragment? x.next = x.next.next b. Singly Linked List has two private instance variables first and last as that point to the first and the last nodes in the list, respectively. Write a fragment of code that removes the last node in a linked list whose first node is first....
Please solve this problem in java. (simple linked list) public class MyLinkedList implements MiniList{ /* Private...
Please solve this problem in java. (simple linked list) public class MyLinkedList implements MiniList{ /* Private member variables that you need to declare: ** The head pointer ** The tail pointer */    private Node head;    private Node tail;       public class Node { // declare member variables (data and next)    Integer data;    Node next; // finish these constructors    public Node(int data, Node next) {               this.data=data;        this.next=next;    }...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT