[英]Implementation of Adjacency list of a graph
我正在嘗試為非加權圖和幾個問題/關注點實現鄰接列表。 我意識到我需要一個鏈表來存儲邊和一個數組來存儲頂點。目前我有一個(基本的)Node類和一個Graph類,它負責將邊添加到特定的頂點。 但是,這並未明確定義邊的鏈接列表。 我想做一個DFS和BFS,並想知道我應該怎么做呢? 我是否需要更改已經包含這些方法的代碼或現在。 幫助將不勝感激。
// 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;
}
}
}
關於您的代碼的一些注意事項:
您使用固定大小的數組來存儲節點。 切換到在添加新節點時自動增長的arraylist。
我是否正確理解您可能只有一條邊緣離開您的節點( next
)? 您還應該在此處使用列表。
只要您的圖表沒有被定向,請注意從A到B的邊緣也從B變為A,因此您必須將它添加到節點A和節點B的邊緣列表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.