📜  在java代码示例中的双链表的最后添加元素

📅  最后修改于: 2022-03-11 14:52:38.053000             🧑  作者: Mango

代码示例1
void push_back(int newElement) {
  
  //1. allocate node
  Node newNode = new Node();
  
  //2. assign data element
  newNode.data = newElement;
  
  //3. assign null to the next and prev
  //   of the new node
  newNode.next = null; 
  newNode.prev = null;

  //4. Check the list is empty or not,
  //   if empty make the new node as head 
  if(head == null) {
    head = newNode;
  } else {
    
    //5. Else, traverse to the last node
    Node temp = new Node();
    temp = head;
    while(temp.next != null)
      temp = temp.next;
    
    //6. Adjust the links
    temp.next = newNode;
    newNode.prev = temp;
  }    
}