简体   繁体   中英

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

I'm currently working on creating a doubly linked list, but I'm struggling to do so because the constructor requires the previous element and the next element. However, checking the list just results in two null elements, the head and the tail. The constructor for a node is

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

The constructor for the empty list that I have is

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

My code for adding an element is

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

I know that the reason I'm resulting in null is because tail == null when I pass it into the constructor. However, I don't know how to update the value of tail before creating a new Node. I tried constructing the empty list with

public DoublyLinkedList() {
    head = tail = null;
    head.prev = null;
    head.next = tail;
    tail.next = null;
    tail.prev = head;
}

But that isn't showing the elements as being added either.

Am going to assume that addElement adds an element to the end of the list if that is the case try this instead

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

For that you can create a class like this: Just for start.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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