Java insert node at end of doubly linked list

www.lautt‮ru‬i.com
Java insert node at end of doubly linked list

To insert a node at the end of a doubly linked list in Java, you can use the following steps:

  1. Create a new node with the data that you want to insert.
  2. Check if the list is empty. If it is, set the new node as the head and tail of the list.
  3. If the list is not empty, set the new node's previous pointer to the current tail of the list, and set the current tail's next pointer to the new node.
  4. Set the new node as the tail of the list.

Here is an example of how to insert a node at the end of a doubly linked list in Java:

public class DoublyLinkedList {
    private class Node {
        int data;
        Node next;
        Node prev;

        public Node(int data) {
            this.data = data;
            this.next = null;
            this.prev = null;
        }
    }

    private Node head;
    private Node tail;

    public void insertAtEnd(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            // The list is empty, so set the new node as the head and tail
            head = newNode;
            tail = newNode;
        } else {
            // The list is not empty, so insert the new node at the end
            newNode.prev = tail;
            tail.next = newNode;
            tail = newNode;
        }
    }
}

In this example, the insertAtEnd() method is used to insert a new node at the end of the doubly linked list. The Node class represents a node in the list, and it has data fields for the data, the next node, and the previous node. If the list is empty, the new node is set as the head and the tail of the list.

Created Time:2017-11-03 23:27:13  Author:lautturi