Implementation of Adjacency list of a graph
I am trying to implement the adjacency list for a non-weighted graph and a few questions/concerns. i realize I need a linked list to store the edges and an array to store the vertices.Currently I have a (basic)Node class and a Graph class, which takes care of the addition of the edges to a particular vertex. This however does not explicitly define a linked list for the edges. I want to do a DFS and BFS and was wondering how should I go about it? Do I need to changed the code that I already have to incorporate 开发者_Go百科these methods or now. Help will be appreciated.
// Inside the graph class
public boolean insertNode(NodeRecord n) {
int j;
if (isFull()) return false;
for (j=0; j<arraySize; j++)
if (node[j]==null)
break;
node[j] = new Node(n);
graphSize++;
return true;
}
public boolean insertEdge(int nodeID, EdgeRecord e) {
int j;
for (j=0; j<arraySize; j++)
if (nodeID==((NodeRecord) node[j].item).getID())
break;
if (j>=arraySize) return false;
node[j].next = new Node(e, node[j].next);
return true;
}
// inside the node class
class Node<E> {
E item;
Node<E> next;
Node(E e) {
item = e;
next = null;
}
Node(E e, Node<E> newNext) {
item = e;
next = newNext;
}
Node(Node<E> n) { // copy constructor
item = n.item;
next = n.next;
}
}
public static void depthFirst(){
for(int i=0;i<mygraph.arraySize;i++){
Node counter =mygraph.node[i];
while(counter!=null){
System.out.println(" " +counter.item);
counter= counter.next;
}
}
}
A few notes on your code:
You use fixed size array to store your nodes. Switch to an arraylist which grows automatically while adding new nodes.
Do I understand correctly that you may only have a single edge leaving your node (
next
)? You should also use a list here.As long as your graph is not directed take care that an edge running from A to B also goes from B to A and thus you have to add it to edge-lists of node A and node B.
精彩评论