循环双链列表为什么我陷入了循环?

问题描述 投票:1回答:2
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);
        }
    }

根据我的理解,在实现循环链接列表时,我必须将列表的尾部指向头部节点。这是我的一个循环双链接列表的实现,注释出来的一行是我不明白为什么会导致错误。好像尾部要么是空的,要么是卡在无限循环中,谁能帮我理解一下,谢谢。

java data-structures doubly-linked-list circular-list
2个回答
0
投票
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);
        }
    }

0
投票

错误的是我的length和toString方法小修改,谢谢帮助。

© www.soinside.com 2019 - 2024. All rights reserved.