【问题标题】:Circular Doubly Linked List why am I stuck in a loop?循环双向链表为什么我会陷入循环?
【发布时间】:2020-04-21 05:36:13
【问题描述】:
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);
        }
    }

据我了解,在实现循环链​​表时,我必须将链表的尾部指向头节点。这是我拥有的双循环链表的实现,注释掉的行是我不明白为什么会导致错误的原因。看起来尾巴要么为空,要么陷入无限循环,有人可以帮我理解吗?谢谢

【问题讨论】:

  • this.tail.nextNode = newNode;我认为 else 语句中缺少。
  • 我也试过了,但 tail.nextNode 仍然给我一个无限循环。

标签: java data-structures doubly-linked-list circular-list


【解决方案1】:
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);
        }
    }

【讨论】:

  • 它仍然进入一个无限循环。 :(
  • @Chabba 把整个代码然后.. 调试一下吧!
  • 啊,我认为它在我的 toString 方法中,让我尝试修复
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-05-27
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 2023-03-22
    • 2016-04-08
    • 2020-07-13
    • 2019-12-23
    • 1970-01-01
    相关资源
    最近更新 更多