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...
how do I create a graph class to store a adjacency list representation of a graph?...
how do I create a graph class to store a adjacency list representation of a graph? I need some help and dont conpletely understand how to start. if you could provide a code with some steps id appreciate it.
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...
Java Generic 2D Linked List Problem How to convert a 1D linked List into multiple linked...
Java Generic 2D Linked List Problem How to convert a 1D linked List into multiple linked lists with sequential values together? //Example 1: [1,1,2,3,3] becomes [[1,1],[2],[3,3]] //Example 1: [1,1,2,1,1,2,2,2,2] becomes [[1,1],[2],[1,1],[2,2,2,2]] //Example 3: [1,2,3,4,5] becomes [[1],[2],[3],[4],[5]] public <T> List<List<T>> convert2D(List<T> list) { // Given a 1D, need to combine sequential values together. }
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)
Remove the minimum element from the linked list in Java public class LinkedList {      ...
Remove the minimum element from the linked list in Java public class LinkedList {       // The LinkedList Node class    private class Node{               int data;        Node next;               Node(int gdata)        {            this.data = gdata;            this.next = null;        }           }       // The LinkedList fields    Node head;       // Constructor    LinkedList(int gdata)   ...
JAVA Write a class for a Stack of characters using a linked list implementation. Write a...
JAVA Write a class for a Stack of characters using a linked list implementation. Write a class for a Queue of characters using a linked list implementation. Write a class for a Queue of integers using a circular array implementation.
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
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT