Can you explain how the insert method works in this Java linked list implementation, and what role the head and tail pointers play in efficiently adding nodes to the list?
The insert(int data) method creates a new node with the given integer value.
If the list is empty (head == null), the new node becomes both the head and tail of the list.
If the list already contains nodes, the new node is added to the end:
The current tail node’s next pointer is updated to reference the new node.
The tail pointer is then updated to point to the new node.
package Interview_practice;
class Node {
public Node(int data) {
this.data = data;
}
int data;// 0
Node next;// null
}
class link_list {
Node head = null, tail = null;
public void insert(int data) {
Node n = new Node(data);
n.next = null;// next null
if (head == null) {
head = n;
tail = n;
} else {
tail.next = n;
tail = n;
}
}
public void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
}
public class Linked_list {
public static void main(String[] args) {
link_list ls = new link_list();
ls.insert(10);
ls.insert(101);
ls.insert(102);
ls.insert(104);
ls.display();
}
}
Output:10 101 102 104
Top comments (0)