简体   繁体   English

循环双向链表为什么我会陷入循环?

[英]Circular Doubly Linked List why am I stuck in a loop?

public class LinkedList<E> {
    private Node<E> head;
    private Node<E> tail;

    /* Inserts*/
    public void insertAtHead(E data)
    {
        Node<E> newNode=new Node<E>(data);
        if(this.head==null)
        {
            this.head=newNode;
            //newNode.nextNode=this.head; <--- Here is error cause
            this.tail=this.head;
        }
        else {
            newNode.prevNode = this.tail;
            this.head.prevNode = newNode;
            newNode.nextNode = this.head;
            this.head = newNode;
            System.out.println("tail.next is: " + this.tail.nextNode);
        }
    }

To my understanding, I must point the tail of the list to the head node when implementing a circular linked list.据我了解,在实现循环链表时,我必须将链表的尾部指向头节点。 This is the implementation of a doubly circular linked list I have and the commented out line is what I do not understand why is causing an error.这是我拥有的双循环链表的实现,注释掉的行是我不明白为什么会导致错误的原因。 It seems like the tail is either null or getting stuck in an infinite loop, can someone help me understand please?看起来尾巴要么是 null 要么陷入无限循环,有人可以帮我理解吗? thank you谢谢你

public void insertAtHead(E data)
    {
        Node<E> newNode=new Node<E>(data);
        if(this.head==null)
        {
            this.head=newNode;
            newNode.nextNode=this.head; // this should NOT be the bug place
            newNode.prevNode=this.head; // add this
            this.tail=this.head;
        }
        else {
            newNode.prevNode = this.tail;
            this.head.prevNode = newNode;
            newNode.nextNode = this.head;
            this.head = newNode;
            tail.nextNode = this.head // add this
            System.out.println("tail.next is: " + this.tail.nextNode);
        }
    }

Error was with my length and toString methods small modification, thanks for help.错误是我的长度和 toString 方法的小修改,谢谢帮助。

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

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