如何初始化一个双向链表,然后在 java 中添加第一个元素?

How can I initialize a Doubly Linked List and then add the first element in java?

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

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

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

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

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

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

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