To insert a node at the end of a doubly linked list in Java, you can use the following steps:
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.