Adding a new node to the list at a specific position is known as Insertion in a linked list. Linked lists are a fundamental data structure consisting of nodes containing data and a reference (or pointer) to the next node in the sequence. It depends on where you want to insert a new node, there are several types of insertion operations in a linked list:
Insertion at the Beginning
Insert a Node after a Given Node in the Linked List
Insert a Node at the End of Linked List
In this blog, we will discuss a linked list problem that has been asked frequently in Interviews. The problem is to inserting in a linked list.
Let's start with a discussion on what linked lists are. A linked list is an ordered set of elements, each holding data and a link containing the address to the next element.
Try theProblemyourself before moving on to the solution.
What is insertion into a linked list?
Linked list insertion refers to the addition of a new element to a linked list data structure.
Example:
Original Linked List: A -> B -> C.
To insert "X" between nodes A and B we need to adjust the pointers such that after insertion we get A -> X -> B -> C
Now let's understand how to insert Elements to a Linked List
You can add elements to either the beginning, middle or end of the linked list. Let us know about them in detail.
1. How to Insert a Node at the Front/Beginning of Linked List
To insert at the beginning of the linked list you can follow the the steps as mentioned below.
1. Create a new node with the new data.
2. Set the next pointer of the new node to point to the current head of the linked list.
3. Next update the head pointer to point to the new node, making it the new first node in the list.
To insert at the beginning of the linked list you can follow the the steps as mentioned below. 1. Create a new node with the new data. 2. Set the next pointer of the new node to point to the current head of the linked list. 3. Next update the head pointer to point to the new node, making it the new first node in the list.
// Insert at begin of LinkedList
struct node
{
int data;
node *next;
node(int x)
{
data=x; // assigning value to data variable
next=NULL; // initially next is NULL
}
};
node *insertbegin(node *head, int data)
{
node *temp = new node(data);
temp -> next = head;
return temp;
}
2. How to Insert a Node after a Given Node in Linked List
The code given below inserts a new node with the specified data at the nth position in the linked list. It handles special cases for the first position, traverses to the (n-1)th node, performs the insertion, and returns the updated head of the list.
// Insert at nth position of LinkedList
node *insertpos(node *head, int position, int data)
{
node *temp = new node(data);
if(position == 1)
{
temp -> next = head;
return temp;
}
node *curr = head;
for(int i = 1;i <= position-2 && curr != NULL; i++)
{
curr = curr -> next;
}
if(curr == NULL)
{
return head;
}
//Insertion and returning head
temp -> next = curr -> next;
curr -> next = temp;
return head;
}
C
C++
C#
Java
Python
Javascript
C
#include <stdio.h> #include <stdlib.h>
struct Node { int data; struct Node* next; };
void insertAfter(struct Node* prev_node, int new_data) { if (prev_node == NULL) { printf("The given previous node cannot be NULL\n"); return; }
public class Node { public int data; public Node next;
public Node(int d) { data = d; next = null; } }
public class LinkedList { Node head;
public void InsertAfter(Node prev_node, int new_data) { if (prev_node == null) { Console.WriteLine("The given previous node cannot be null"); return; }
public void insertAfter(Node prev_node, int new_data) { if (prev_node == null) { System.out.println("The given previous node cannot be NULL"); return; }
public void printList() { Node n = head; while (n != null) { System.out.print(n.data + " "); n = n.next; } }
public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.head = new Node(1); Node second = new Node(2); llist.head.next = second;
The code given below inserts a new node with the desired data at the end of the linked list. It handles the case when the list is empty, traverses to the last node, performs the insertion, and returns the updated head of the list.
// insert at end of LinkedList
node *insertend(node *head, int data)
{
node *temp = new node(data);
if(head == NULL)
{
return temp;
}
node *curr = head;
while(curr->next != NULL)
{
curr = curr -> next;
}
curr -> next = temp;
temp -> next = NULL;
return head;
}
Now, we will discuss the approach to Insert a node at a specific position in a linked list.
Declare the structure of the Node and write the function to create and return the node.
⬇
For inserting the Node, check whether the required position is valid.
⬇
Create a new Node
⬇
Traverse till the position asked.
⬇
Update the link
1)New Node should point to the old Node at the same position.
2) Change the pointer of the Node previous to the old Node to point to the new Node
Time Complexity = O(n). In the worst case, you have to traverse the whole LinkedList.
Until now, I assume you must have understood what has been asked in the problem statement. So, I strongly recommend you try it and solve some related problems on the linked list. Refer to this article for more problems, Some Commonly Asked Problems On Linked List. Don't be sad if you cannot solve how to Insert a node at a specific position in a linked list. This is part of the learning process.
Please have a look at the algorithm, and then again, you must give it a try.
LinkedList Operations in Python, Java, C, and C++
Python
Java
C
C++
Python
class Node: def __init__(self, data): self.data = data self.next = None
class LinkedList: def __init__(self): self.head = None
def append(self, data): new_node = Node(data) if not self.head: self.head = new_node return last_node = self.head while last_node.next: last_node = last_node.next last_node.next = new_node
def display(self): current = self.head while current: print(current.data, end=" ") current = current.next print()
# Example Usage linked_list = LinkedList() linked_list.append(1) linked_list.append(2) linked_list.append(3) linked_list.display()
You can also try this code with Online Python Compiler
public void append(int data) { Node new_node = new Node(data); if (head == null) { head = new_node; return; } Node last_node = head; while (last_node.next != null) { last_node = last_node.next; } last_node.next = new_node; }
public void display() { Node current = head; while (current != null) { System.out.print(current.data + " "); current = current.next; } System.out.println(); } }
// Example Usage public class Main { public static void main(String[] args) { LinkedList linkedList = new LinkedList(); linkedList.append(1); linkedList.append(2); linkedList.append(3); linkedList.display(); } }
You can also try this code with Online Java Compiler
Where can insertion in a linked list be done from?
Insertion in a linked list can be done from any node because each node in the linked list contains a reference to its next node. So its easy to find node and attach a node next to it.
Why is insertion easy in a linked list?
Insertion is easy in a linked list because there is no need to shift any of the existing nodes in the list. We simply update the next pointer of the previous node to point to the new node.
Is insertion order maintained in LinkedList?
Yes, the insertion order is maintained in a linked list. This is because the next pointer of each node point to its next node in the list, so the order of the nodes remains the same.
How do you insert a linked list in order?
To insert a node into a sorted linked list, traverse the list to find the correct position where the node's value is less than or equal to the next node. Insert the new node at this position, ensuring the list remains ordered.
Conclusion
This article taught us about Insertion in Linked List. We discussed its implementation using illustrations, pseudocode, and then proper code. We hope you can take away critical techniques like analyzing problems by walking over the execution of the examples and finding out the recursive pattern followed in most linked list problems. You can have a look at these articles for more understanding.