简体   繁体   中英

Stuck inside an infinite loop when adding a node in linked list

I've been struggling to figure out why this code is stuck in an infinite loop. The back story is I have found the solution, I changed the constructor to assign head is equal to null and that fixed it.

I wonder why this code is NOT working.

When I add different nodes, it is working. The code works as expected.

Issues arise when adding the same node.

public class Main {
    public static void main(String[] args) {
        Node one = new Node(1);
        Node two = new Node(2);

        LinkedList list = new LinkedList(one);
        // this gives error, if i add the same nodes
        list.add(two);
        list.add(two);

        System.out.println("Printing out:\n" + list.toString() +"\n");
    }
}


public class LinkedList {
    Node head;
    int length = 0;
    public boolean isEmpty() {
        return (head==null);
    }

    public String toString() {
        Node current = head;
        String string = "Head: ";

        while(current.next != null) {
            string += current.toString() + " --> ";
            current = current.next;
        }
        string += current.toString() + " --> " + current.next;
        return string;
    }

    public LinkedList(Node node) {
        // if were to set head to null and no arg, it works fine
        head = node;
        length = 1;
    }

    public void add(Node node) {
        if(isEmpty()) {
            System.out.println("Empty list, adding node...");
            head = new Node(node.data); ++length;
            return;
        }
        else {

        Node current = head;
        while(current.next != null) {
            current = current.next;
        }
        //current.next = new Node(node.data);
        current.next = node;
        ++length;
        return;
        }
    }

The error is, it never terminates, hence why I think it is forever looping.

I think in your add(Node node) code. When you adding same node twice, it will point the next to itself. Therefore it would be infinite loop.

Its going in infinte loop because of while loop in toString() method of LinkedList class.

you are validating on condition

while(current.next != null) { .....}

after reaching on last node, you are not setting next of last node to null, so the condition will never terminate.

To resolve this where you are adding node point node.next = null;

        current.next = node;
        node.next = null;
        ++length;
        return;

It will terminate and will not go in infinte loop

The line in your code not fine is in add method 'current.next=node'. Try to change it to 'current.next=new Node(node.data)'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM