Search code examples
loopslinked-listcircular-list

Infinite Linked List issue


I'm trying to construct a node list, and I believe the list turns into a loop, but I cannot figure out how! Below are the two methods that are used to do this.

GraphNode Class

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 method (numNodes = 19, it reads from input file)

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 method

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;
    }
}

This should insert each node in ascending order by the numEdges in each node. But when I try to print out the linked list after each insert, it prints out an unlimited amount of what I believe to be the first node in the list.


Solution

  • After almost an entire day of asking people, searching online, etc, one person finally knew what was wrong.

    Such a simple thing, as usual! The constructNodeList method re-uses the same node every time! So the same node gets re-written, creating the same "next" node of the inserted node. So, to fix this, the new method is now:

    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);
        }
    }