我正在尝试构建一个节点列表,我相信这个列表变成了一个循环,但我无法弄清楚如何!以下是用于执行此操作的两种方法。
GraphNode类
public class GraphNode {
public int nodeID;
public int color;
public int numEdges;
public GraphNode next;
public GraphNode() {
nodeID = 0;
color = 0;
numEdges = 0;
next = null;
}
public GraphNode(int id, int e) {
nodeID = id;
color = 0;
numEdges = e;
next = null;
}
public void setNext (GraphNode next) { this.next = next; } }
constructNodeList方法(numNodes = 19,它从输入文件中读取)
public void constructNodeList(GraphNode p) {
int edgeCount;
for (int i = 0; i < numNodes; i++) {
edgeCount = 0;
for (int j = 0; j < numNodes; j++) {
System.out.println((i+1) + ", " + (j+1) + ": " + adjMatrix[i][j]);
if (adjMatrix[i][j] == 1) edgeCount++;
}
p.nodeID = i+1;
p.numEdges = edgeCount;
System.out.println(p.nodeID + ": " + p.numEdges);
insertOneNode(p);
}
}
insertOneNode方法
public void insertOneNode(GraphNode newNode) {
GraphNode current = listHead;
GraphNode temp = current;
while (current.next != null && newNode.numEdges > current.next.numEdges) {
current = current.next;
}
if (current.next == null) current.setNext(newNode);
else {
temp = current.next;
current.setNext(newNode);
newNode.next = temp;
}
}
这应该按每个节点中的numEdges按升序插入每个节点。但是当我尝试在每次插入后打印出链表时,它会打印出无限量的我认为是列表中的第一个节点。
答案 0 :(得分:0)
经过近一整天的询问,在线搜索等,一个人终于知道出了什么问题。
像往常一样这么简单! constructNodeList方法每次都重用相同的节点!因此,相同的节点被重写,创建相同的&#34; next&#34;插入节点的节点。所以,为了解决这个问题,新方法现在是:public void constructNodeList() {
int edgeCount;
for (int i = 0; i < numNodes; i++) {
edgeCount = 0;
for (int j = 0; j < numNodes; j++) {
//System.out.println((i+1) + ", " + (j+1) + ": " + adjMatrix[i][j]);
if (adjMatrix[i][j] == 1 && i != j) edgeCount++;
}
GraphNode p = new GraphNode(); // new node every time!
p.nodeID = i+1;
p.numEdges = edgeCount;
System.out.println(p.nodeID + ": " + p.numEdges);
insertOneNode(p);
}
}