【问题标题】:How can I initialize a Doubly Linked List and then add the first element in java?如何初始化双向链表,然后在 java 中添加第一个元素?
【发布时间】:2018-01-05 17:11:59
【问题描述】:

我目前正在创建一个双向链表,但我正在努力这样做,因为构造函数需要前一个元素和下一个元素。但是,检查列表只会产生两个空元素,头部和尾部。节点的构造函数是

    public Node(Node prev, Node next, String link) {
        this.prev = prev;
        this.next = next;
        this.link = link;
    }

我拥有的空列表的构造函数是

public DoublyLinkedList() {
    head = tail = null;
}

我添加元素的代码是

public void addElement(String link) {
    Node n = new Node(tail.prev, tail, link);
    if (head == null) {
        head = n;
        head.next = n;
    }
    tail.prev = n;
    tail = n;
}

我知道导致 null 的原因是因为 tail == null 当我将它传递给构造函数时。但是,我不知道如何在创建新节点之前更新 tail 的值。我尝试用

构建空列表
public DoublyLinkedList() {
    head = tail = null;
    head.prev = null;
    head.next = tail;
    tail.next = null;
    tail.prev = head;
}

但这也没有显示元素被添加。

【问题讨论】:

  • 如果没有明确定义“不起作用”是什么意思,我们无法为您提供帮助。
  • @JoeC 我在帖子中,当我尝试实际检查列表时,我只得到空元素,头部和尾部。为了清楚起见,我进行了编辑。
  • 看来你需要学习使用调试器了。请帮助自己一些complementary debugging techniques。如果您之后仍有问题,请随时回来提出更具体的问题。
  • 我知道如何使用调试器。我问为什么,当我打印列表时,它只打印一个元素:null。
  • 打印语句在哪里?

标签: java nodes doubly-linked-list


【解决方案1】:

我将假设addElement 将一个元素添加到列表的末尾 如果是这样的话,试试这个

Node n = new Node(tail, null, link); // The new tail
if (head == null) {
    head = n;
    tail = n;
}else{
    tail.next = n;
    tail = n;
}

【讨论】:

    【解决方案2】:

    为此,您可以创建一个这样的类: 刚刚开始。

    public class DLinkedList{
      private node pHead;
      private node pTail;
    
      public DLinkedList()
      {
          this.pHead=null;
          this.pTail=null;
      }
    
       public insert(String newLink)
       {
           node newNode = new node():
           newNode.link = newLink;
           if(pHead==null)
           {
              pHead=newNode;
              pTail=pHead;
          }
          else
          {
              newNode.prev=pTail;
              pTail.next=newNode;
              pTail= pTail.next;
           }
       }
    }
    

    【讨论】:

    • 我不在家,所以我用手机做了这个。很抱歉没有提供更多帮助
    • Lists 是我喜欢使用的东西。通常我用 C 来做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 2015-03-14
    • 1970-01-01
    相关资源
    最近更新 更多