Insert Node at the beginning of a Linked List in 5 minutes

When we have a linked list we might need to add/ insert a node in the beginning of a linked list. If you want to know more about what is a linked list, check out a detailed guide on linked list here. Here, in this tutorial, let us try to insert a node in the beginning of a linked list. We will consider Java for this example.

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 addNodeInBegining(int value) {
		Node currentNode = this.head;
		Node newNodeToAdd = new Node(value);
		
		newNodeToAdd.next = currentNode;
		this.head = newNodeToAdd;
	}

         public void showList() {
		Node currentNode = this.head;
		while(currentNode != null) {
			System.out.println(currentNode.value);
			currentNode = currentNode.next;
		}
	}

         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 begining");
		linkedList.addNodeInBegining(10);
		linkedList.showList();
         }
}
Output

11
12
13
14
15
--------------------
After Adding node in the begining
10
11
12
13
14
15

The above program gives us the approach to add a node in the beginning of a linked list. Let us now go through the algorithm in details.

To add a node in the beginning, we start by creating a method addNodeInBegining(int value) which takes the value of the node in the method parameter. Now we initialize a new Node (temporary) in the method with the value passed in the method parameter. Next, the currentNode we initialize is set to the head position. So, we update the next pointer of the new node to the currentNode and the head pointer is updated to the new node we created. This is being done within the method by the following piece of code:

newNodeToAdd.next = currentNode;
this.head = newNodeToAdd;

Since, this adds a node in the beginning itself and there are no requirement to loop through the whole list, the time complexity becomes O(1).

Leave a Comment