Insert a Node after a given Node in Linked List
Last Updated :
29 Jul, 2024
Given a linked list, the task is to insert a new node after a given node of the linked list. If the given node is not present in the linked list, print "Node not found".
Examples:
Input: LinkedList = 2 -> 3 -> 4 -> 5, newData = 1, key = 2
Output: LinkedList = 2 -> 1 -> 3 -> 4 -> 5
Input: LinkedList = 1 -> 3 -> 5 -> 7, newData = 1, key = 2
Output: Node not found
Approach: To solve the problem, follow the below idea:
If we want to insert a new node after a given node, we first locate that node. If the node is not found, print "Node not found". If we find it, we set the new node's next reference to point to the node that follows the given node. Then, we update the given node's next to point to the new node.
Follow the below steps for inserting a node after a given node:
- Traverse the linked list to find the given node.
- If the given node is not found, print "Node not found".
- Else if the given node is found, create a new node, say new_node initialized with the given data.
- Make the next pointer of new_node as next of given node.
- Update the next pointer of given node point to the new_node.
Below is the implementation of the approach:
C++
// C++ Program to insert a node after a given node
#include <bits/stdc++.h>
using namespace std;
// Definition of a linked list node
struct Node {
int data;
Node* next;
// Constructor to initialize the node
Node(int data) {
this->data = data;
this->next = nullptr;
}
};
// Function to insert a new node after a given node
Node* insertAfter(Node* head, int key, int newData) {
Node* curr = head;
// Iterate over Linked List to find the key
while (curr != nullptr) {
if (curr->data == key)
break;
curr = curr->next;
}
// if curr becomes NULL means, given key is not
// found in linked list
if (curr == nullptr) {
cout << "Node not found" << endl;
// Return the head of the original linked list
return head;
}
// Allocate new node and make the element to be inserted
// as a new node
Node* newNode = new Node(newData);
// Set the next pointer of new node to the next pointer of given node
newNode->next = curr->next;
// Change the next pointer of given node to the new node
curr->next = newNode;
// Return the head of the modified linked list
return head;
}
// Function to print the linked list
void printList(Node* node)
{
while (node != nullptr) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
// Driver code
int main() {
// Create a hard-coded linked list:
// 2 -> 3 -> 5 -> 6
Node* head = new Node(2);
head->next = new Node(3);
head->next->next = new Node(5);
head->next->next->next = new Node(6);
cout << "Original Linked List: ";
printList(head);
// Key: Insert node after key
int key = 3, newData = 4;
// Insert a new node with data 4 after the node having
// data 3
head = insertAfter(head, key, newData);
cout << "Linked List after insertion: ";
printList(head);
return 0;
}
C
// C Program to insert a node after a given node
#include <stdio.h>
#include <stdlib.h>
// Definition of a linked list node
struct Node {
int data;
struct Node* next;
};
// Function to create and return a new node
struct Node* createNode(int data) {
struct Node* newNode
= (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert a new node after a given node and
// return the head of modified list
struct Node* insertAfter(struct Node* head, int key,
int newData) {
// Initialize curr Pointer to head
struct Node* curr = head;
// Iterate over Linked List to find the key
while (curr != NULL) {
if (curr->data == key)
break;
curr = curr->next;
}
// if curr becomes NULL means, given key is not found in
// linked list
if (curr == NULL) {
printf("Node not found\n");
// Return the head of the original linked list
return head;
}
// Allocate new node and make the element to be inserted
// as a new node
struct Node* newNode
= (struct Node*)malloc(sizeof(struct Node));
newNode->data = newData;
// Set the next pointer of new node to the next pointer
// of given node
newNode->next = curr->next;
// Change the next pointer of given node to the new node
curr->next = newNode;
// Return the head of the modified linked list
return head;
}
// Function to print the linked list
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
// Driver code
int main() {
// Create the linked list 2 -> 3 -> 5 -> 6
struct Node* head = createNode(2);
head->next = createNode(3);
head->next->next = createNode(5);
head->next->next->next = createNode(6);
printf("Original Linked List: ");
printList(head);
// Key: Insert node after key
int key = 3, newData = 4;
// Insert a new node with data 4 after the node with data 3
head = insertAfter(head, key, newData);
printf("Linked List after insertion: ");
printList(head);
return 0;
}
Java
// Java Program to insert a node after a given node
// Definition of a linked list node
class Node {
int data;
Node next;
// Constructor to initialize the node
Node(int data) {
this.data = data;
this.next = null;
}
}
// Driver code
public class GFG {
// Function to insert a new node after a given node
public static Node insertAfter(Node head, int key, int newData) {
// Initialize curr Pointer to head
Node curr = head;
// Iterate over Linked List to find the key
while (curr != null) {
if (curr.data == key)
break;
curr = curr.next;
}
// If curr becomes null means, given key is not
// found in linked list
if (curr == null) {
System.out.println("Node not found");
// Return the head of the original linked list
return head;
}
// Allocate new node and make the element to be
// inserted as a new node
Node newNode = new Node(newData);
// Set the next pointer of new node to the next
// pointer of given node
newNode.next = curr.next;
// Change the next pointer of given node to the
// new node
curr.next = newNode;
// Return the head of the modified linked list
return head;
}
// Function to print the linked list
public static void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
public static void main(String[] args) {
// Create the linked list 2 -> 3 -> 5 -> 6
Node head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(5);
head.next.next.next = new Node(6);
System.out.print("Original Linked List: ");
printList(head);
// Key: Insert node after key
int key = 3, newData = 4;
// Insert a new node with data 4 after the node
// having data 3
head = insertAfter(head, key, newData);
System.out.print("Linked List after insertion: ");
printList(head);
}
}
Python
# Python Program to insert a node after a given node
# Definition of a linked list node
class Node:
# Constructor to initialize the node
def __init__(self, data):
self.data = data
self.next = None
# Function to insert a new node after a given node
def insert_after(head, key, new_data):
curr = head
# Iterate over Linked List to find the key
while curr is not None:
if curr.data == key:
break
curr = curr.next
# if curr becomes None means, given key is not
# found in linked list
if curr is None:
print("Node not found")
# Return the head of the original linked list
return head
# Allocate new node and make the element to be inserted
# as a new node
new_node = Node(new_data)
# Set the next pointer of new node to the next pointer of given node
new_node.next = curr.next
# Change the next pointer of given node to the new node
curr.next = new_node
# Return the head of the modified linked list
return head
# Function to print the linked list
def print_list(node):
while node is not None:
print(node.data, end=" ")
node = node.next
print()
# Driver code
if __name__ == "__main__":
# Create a hard-coded linked list:
# 2 -> 3 -> 5 -> 6
head = Node(2)
head.next = Node(3)
head.next.next = Node(5)
head.next.next.next = Node(6)
print("Original Linked List: ", end="")
print_list(head)
# Key: Insert node after key
key = 3
new_data = 4
# Insert a new node with data 4 after the node having
# data 3
head = insert_after(head, key, new_data)
print("Linked List after insertion: ", end="")
print_list(head)
C#
// C# Program to insert a node after a given node
using System;
// Definition of a linked list node
class Node
{
public int Data;
public Node Next;
// Constructor to initialize the node
public Node(int data) {
this.Data = data;
this.Next = null;
}
}
class GFG {
// Function to insert a new node after a given node
static Node InsertAfter(Node head, int key, int newData) {
Node curr = head;
// Iterate over Linked List to find the key
while (curr != null) {
if (curr.Data == key)
break;
curr = curr.Next;
}
// if curr becomes null means, given key is not
// found in linked list
if (curr == null) {
Console.WriteLine("Node not found");
// Return the head of the original linked list
return head;
}
// Allocate new node and make the element to be inserted
// as a new node
Node newNode = new Node(newData);
// Set the next pointer of new node to the next pointer of given node
newNode.Next = curr.Next;
// Change the next pointer of given node to the new node
curr.Next = newNode;
// Return the head of the modified linked list
return head;
}
// Function to print the linked list
static void PrintList(Node node) {
while (node != null) {
Console.Write(node.Data + " ");
node = node.Next;
}
Console.WriteLine();
}
// Driver code
static void Main() {
// Create a hard-coded linked list:
// 2 -> 3 -> 5 -> 6
Node head = new Node(2);
head.Next = new Node(3);
head.Next.Next = new Node(5);
head.Next.Next.Next = new Node(6);
Console.Write("Original Linked List: ");
PrintList(head);
// Key: Insert node after key
int key = 3, newData = 4;
// Insert a new node with data 4 after the node having
// data 3
head = InsertAfter(head, key, newData);
Console.Write("Linked List after insertion: ");
PrintList(head);
}
}
JavaScript
// Javascript Program to insert a node after a given node
// Definition of a linked list node
class Node {
// Constructor to initialize the node
constructor(data)
{
this.data = data;
this.next = null;
}
}
// Function to insert a new node after a given node
function insertAfter(head, key, newData) {
let curr = head;
// Iterate over Linked List to find the key
while (curr !== null) {
if (curr.data === key) {
break;
}
curr = curr.next;
}
// if curr becomes null means, given key is not
// found in linked list
if (curr === null) {
console.log("Node not found");
// Return the head of the original linked list
return head;
}
// Allocate new node and make the element to be inserted
// as a new node
let newNode = new Node(newData);
// Set the next pointer of new node to the next pointer
// of given node
newNode.next = curr.next;
// Change the next pointer of given node to the new node
curr.next = newNode;
// Return the head of the modified linked list
return head;
}
// Function to print the linked list
function printList(node) {
while (node !== null) {
console.log(node.data + " ");
node = node.next;
}
console.log();
}
// Driver code
// Create a hard-coded linked list:
// 2 -> 3 -> 5 -> 6
let head = new Node(2);
head.next = new Node(3);
head.next.next = new Node(5);
head.next.next.next = new Node(6);
console.log("Original Linked List: ");
printList(head);
// Key: Insert node after key
let key = 3, newData = 4;
// Insert a new node with data 4 after the node having
// data 3
head = insertAfter(head, key, newData);
console.log("Linked List after insertion: ");
printList(head);
OutputOriginal Linked List: 2 3 5 6
Linked List after insertion: 2 3 4 5 6
Time Complexity: O(N), where N is the number of nodes in the linked list.
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem