繁体   English   中英

在链表中添加节点时陷入无限循环

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

我一直在努力弄清楚为什么这段代码会陷入无限循环。 背后的故事是我找到了解决方案,我将构造函数更改为分配 head 等于 null 并修复了它。

我想知道为什么这段代码不起作用。

当我添加不同的节点时,它正在工作。 该代码按预期工作。

添加相同节点时会出现问题。

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

错误是,它永远不会终止,因此我认为它永远在循环。

我认为在您的 add(Node node) 代码中。 当您添加两次相同的节点时,它会将下一个指向自身。 因此这将是无限循环。

由于 LinkedList class 的 toString() 方法中的 while 循环,它进入无限循环。

您正在条件验证

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

到达最后一个节点后,您没有将最后一个节点的下一个节点设置为 null,因此条件永远不会终止。

要解决此问题,您要添加节点点 node.next = null;

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

它将终止并且不会在无限循环中 go

代码中的行不正确是在添加方法“current.next=node”中。 尝试将其更改为 'current.next=new Node(node.data)'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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