Insert node at the end of a Linked List in 5 minutes

When we have a linked list, we want to add a node in the end of a linked list. Let us first try to figure out the intuition behind the algorithm.

We start by iterating the list so that we get to the last node of the linked list. Next, we add the new node of the linked list to the next pointer of the last node. Finally, we update the next pointer of the new node as null. Let’s look at this via a linked list program.

public class LinkedList {

	// Creating a sub class Node. This will act as each node of a linkedlist
	class Node {
		int value;
		Node next;

		Node(int value){
			this.value = value;
			this.next = null;
		}
	}

	Node head;

	public void addNode(int value) {
		Node newNodeToAdd = new Node(value);
		if(head == null) {
			this.head = newNodeToAdd;
		} else {
			Node tail = this.head;
			while (tail.next != null) {
				tail = tail.next;
			}
			tail.next = newNodeToAdd;
		}
		
	}

         public void addNodeInEnd(int value) {
		Node currentNode = this.head;
		Node newNodeToAdd = new Node(value);
		
		while(currentNode.next != null) {
			currentNode = currentNode.next;
		}
		currentNode.next = newNodeToAdd;
		newNodeToAdd.next = null;
	}

         public static void main(String[] args) {
		LinkedList linkedList = new LinkedList();
		
		linkedList.addNode(11);
		linkedList.addNode(12);
		linkedList.addNode(13);
		linkedList.addNode(14);
		linkedList.addNode(15);
		
		linkedList.showList();
		System.out.println("--------------------");
		
		System.out.println("After adding node in the end");
		linkedList.addNodeInEnd(16);
		linkedList.showList();
          }
 }
Output:

11
12
13
14
15
--------------------
After adding node in the end
10
11
12
13
14
15
16

Here in the above code, the method addNodeInEnd(int value) the code starts by initializing a new node and a currentNode variable starting from the head position. Then we continue to loop until the next pointer of the current node is null. It means we have reached the last position. Now we update the next pointer of this currentNode to the new node. Then the next pointer of the new node is updated to null. This will add a node at the end of the linked list. The method addNode adds normally. We have discussed about the general method in a detailed tutorial about linked list. Check out here.

Leave a Comment