[英]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.