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...
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;    }...
First, create a project that creates an ordered linked list class (use the code provided, make...
First, create a project that creates an ordered linked list class (use the code provided, make sure to update the insert function so that it maintains an ordered list). To this class, add a function that prints the list in REVERSE order. Making use of recursion is the easiest and best way to do this, but certainly not the only way. Submit a .zip of your entire project.
Write a subroutine named swap in C thatswaps two nodes in a linked list. The first...
Write a subroutine named swap in C thatswaps two nodes in a linked list. The first node should not be able to change places. The nodes are given by: Struct nodeEl { int el; struct nodeEl * next; }; typdef struct nodeEl node; The list header (of type node *) is the first parameter of the subroutine. The second and third parameters consist of integers and are the places in the list where the nodes are to change places. The...
Suppose a linked list of 20 nodes. The middle node has a data –250. Write the...
Suppose a linked list of 20 nodes. The middle node has a data –250. Write the pseudocode to replace the middle node of the linked list with a new node and new data. Assume that the list's head pointer is called head_ptr and the data for the new node is called entry
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT