Insert a node after the n-th node from the end
Last Updated :
02 Jan, 2023
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n.
Examples:
Input : list: 1->3->4->5
n = 4, x = 2
Output : 1->2->3->4->5
4th node from the end is 1 and
insertion has been done after this node.
Input : list: 10->8->3->12->5->18
n = 2, x = 11
Output : 10->8->3->12->5->11->18
Method 1 (Using length of the list): Find the length of the linked list, i.e, the number of nodes in the list. Let it be len. Now traverse the list from the 1st node upto the (len-n+1)th node from the beginning and insert the new node after this node. This method requires two traversals of the list.
Implementation:
C++
// C++ implementation to insert a node after
// the n-th node from the end
#include <bits/stdc++.h>
using namespace std;
// structure of a node
struct Node {
int data;
Node* next;
};
// function to get a new node
Node* getNode(int data)
{
// allocate memory for the node
Node* newNode = (Node*)malloc(sizeof(Node));
// put in the data
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// function to insert a node after the
// nth node from the end
void insertAfterNthNode(Node* head, int n, int x)
{
// if list is empty
if (head == NULL)
return;
// get a new node for the value 'x'
Node* newNode = getNode(x);
Node* ptr = head;
int len = 0, i;
// find length of the list, i.e, the
// number of nodes in the list
while (ptr != NULL) {
len++;
ptr = ptr->next;
}
// traverse up to the nth node from the end
ptr = head;
for (i = 1; i <= (len - n); i++)
ptr = ptr->next;
// insert the 'newNode' by making the
// necessary adjustment in the links
newNode->next = ptr->next;
ptr->next = newNode;
}
// function to print the list
void printList(Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program to test above
int main()
{
// Creating list 1->3->4->5
Node* head = getNode(1);
head->next = getNode(3);
head->next->next = getNode(4);
head->next->next->next = getNode(5);
int n = 4, x = 2;
cout << "Original Linked List: ";
printList(head);
insertAfterNthNode(head, n, x);
cout << "\nLinked List After Insertion: ";
printList(head);
return 0;
}
// This code is contributed by Sania Kumari Gupta (kriSania804)
C
// C implementation to insert a node after
// the n-th node from the end
#include <stdio.h>
#include <stdlib.h>
// structure of a node
typedef struct Node {
int data;
struct Node* next;
} Node;
// function to get a new node
Node* getNode(int data)
{
// allocate memory for the node
Node* newNode = (Node*)malloc(sizeof(Node));
// put in the data
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// function to insert a node after the
// nth node from the end
void insertAfterNthNode(Node* head, int n, int x)
{
// if list is empty
if (head == NULL)
return;
// get a new node for the value 'x'
Node* newNode = getNode(x);
Node* ptr = head;
int len = 0, i;
// find length of the list, i.e, the
// number of nodes in the list
while (ptr != NULL) {
len++;
ptr = ptr->next;
}
// traverse up to the nth node from the end
ptr = head;
for (i = 1; i <= (len - n); i++)
ptr = ptr->next;
// insert the 'newNode' by making the
// necessary adjustment in the links
newNode->next = ptr->next;
ptr->next = newNode;
}
// function to print the list
void printList(Node* head)
{
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
}
// Driver program to test above
int main()
{
// Creating list 1->3->4->5
Node* head = getNode(1);
head->next = getNode(3);
head->next->next = getNode(4);
head->next->next->next = getNode(5);
int n = 4, x = 2;
printf("Original Linked List: ");
printList(head);
insertAfterNthNode(head, n, x);
printf("\nLinked List After Insertion: ");
printList(head);
return 0;
}
// This code is contributed by Sania Kumari Gupta (kriSania804)
Java
// Java implementation to insert a node after
// the n-th node from the end
class GfG
{
// structure of a node
static class Node
{
int data;
Node next;
}
// function to get a new node
static Node getNode(int data)
{
// allocate memory for the node
Node newNode = new Node();
// put in the data
newNode.data = data;
newNode.next = null;
return newNode;
}
// function to insert a node after the
// nth node from the end
static void insertAfterNthNode(Node head, int n, int x)
{
// if list is empty
if (head == null)
return;
// get a new node for the value 'x'
Node newNode = getNode(x);
Node ptr = head;
int len = 0, i;
// find length of the list, i.e, the
// number of nodes in the list
while (ptr != null)
{
len++;
ptr = ptr.next;
}
// traverse up to the nth node from the end
ptr = head;
for (i = 1; i <= (len - n); i++)
ptr = ptr.next;
// insert the 'newNode' by making the
// necessary adjustment in the links
newNode.next = ptr.next;
ptr.next = newNode;
}
// function to print the list
static void printList(Node head)
{
while (head != null)
{
System.out.print(head.data + " ");
head = head.next;
}
}
// Driver code
public static void main(String[] args)
{
// Creating list 1->3->4->5
Node head = getNode(1);
head.next = getNode(3);
head.next.next = getNode(4);
head.next.next.next = getNode(5);
int n = 4, x = 2;
System.out.print("Original Linked List: ");
printList(head);
insertAfterNthNode(head, n, x);
System.out.println();
System.out.print("Linked List After Insertion: ");
printList(head);
}
}
// This code is contributed by prerna saini
Python3
# Python implementation to insert a node after
# the n-th node from the end
# Linked List node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# function to get a new node
def getNode(data) :
# allocate memory for the node
newNode = Node(0)
# put in the data
newNode.data = data
newNode.next = None
return newNode
# function to insert a node after the
# nth node from the end
def insertAfterNthNode(head, n, x) :
# if list is empty
if (head == None) :
return
# get a new node for the value 'x'
newNode = getNode(x)
ptr = head
len = 0
i = 0
# find length of the list, i.e, the
# number of nodes in the list
while (ptr != None) :
len = len + 1
ptr = ptr.next
# traverse up to the nth node from the end
ptr = head
i = 1
while ( i <= (len - n) ) :
ptr = ptr.next
i = i + 1
# insert the 'newNode' by making the
# necessary adjustment in the links
newNode.next = ptr.next
ptr.next = newNode
# function to print the list
def printList( head) :
while (head != None):
print(head.data ,end = " ")
head = head.next
# Driver code
# Creating list 1->3->4->5
head = getNode(1)
head.next = getNode(3)
head.next.next = getNode(4)
head.next.next.next = getNode(5)
n = 4
x = 2
print("Original Linked List: ")
printList(head)
insertAfterNthNode(head, n, x)
print()
print("Linked List After Insertion: ")
printList(head)
# This code is contributed by Arnab Kundu
C#
// C# implementation to insert a node after
// the n-th node from the end
using System;
class GfG
{
// structure of a node
public class Node
{
public int data;
public Node next;
}
// function to get a new node
static Node getNode(int data)
{
// allocate memory for the node
Node newNode = new Node();
// put in the data
newNode.data = data;
newNode.next = null;
return newNode;
}
// function to insert a node after the
// nth node from the end
static void insertAfterNthNode(Node head, int n, int x)
{
// if list is empty
if (head == null)
return;
// get a new node for the value 'x'
Node newNode = getNode(x);
Node ptr = head;
int len = 0, i;
// find length of the list, i.e, the
// number of nodes in the list
while (ptr != null)
{
len++;
ptr = ptr.next;
}
// traverse up to the nth node from the end
ptr = head;
for (i = 1; i <= (len - n); i++)
ptr = ptr.next;
// insert the 'newNode' by making the
// necessary adjustment in the links
newNode.next = ptr.next;
ptr.next = newNode;
}
// function to print the list
static void printList(Node head)
{
while (head != null)
{
Console.Write(head.data + " ");
head = head.next;
}
}
// Driver code
public static void Main(String[] args)
{
// Creating list 1->3->4->5
Node head = getNode(1);
head.next = getNode(3);
head.next.next = getNode(4);
head.next.next.next = getNode(5);
int n = 4, x = 2;
Console.Write("Original Linked List: ");
printList(head);
insertAfterNthNode(head, n, x);
Console.WriteLine();
Console.Write("Linked List After Insertion: ");
printList(head);
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// JavaScript implementation to
// insert a node after
// the n-th node from the end
// structure of a node
class Node {
constructor() {
this.data = 0;
this.next = null;
}
}
// function to get a new node
function getNode(data) {
// allocate memory for the node
var newNode = new Node();
// put in the data
newNode.data = data;
newNode.next = null;
return newNode;
}
// function to insert a node after the
// nth node from the end
function insertAfterNthNode(head , n , x) {
// if list is empty
if (head == null)
return;
// get a new node for the value 'x'
var newNode = getNode(x);
var ptr = head;
var len = 0, i;
// find length of the list, i.e, the
// number of nodes in the list
while (ptr != null) {
len++;
ptr = ptr.next;
}
// traverse up to the nth node from the end
ptr = head;
for (i = 1; i <= (len - n); i++)
ptr = ptr.next;
// insert the 'newNode' by making the
// necessary adjustment in the links
newNode.next = ptr.next;
ptr.next = newNode;
}
// function to print the list
function printList(head) {
while (head != null) {
document.write(head.data + " ");
head = head.next;
}
}
// Driver code
// Creating list 1->3->4->5
var head = getNode(1);
head.next = getNode(3);
head.next.next = getNode(4);
head.next.next.next = getNode(5);
var n = 4, x = 2;
document.write("Original Linked List: ");
printList(head);
insertAfterNthNode(head, n, x);
document.write();
document.write("<br/>Linked List After Insertion: ");
printList(head);
// This code contributed by gauravrajput1
</script>
OutputOriginal Linked List: 1 3 4 5
Linked List After Insertion: 1 2 3 4 5
Time Complexity: O(n), where n is the number of nodes in the list.
Auxiliary Space: O(1)
Method 2 (Single traversal): This method uses two pointers, one is slow_ptr and the other is fast_ptr. First move the fast_ptr up to the nth node from the beginning. Make the slow_ptr point to the 1st node of the list. Now, simultaneously move both the pointers until fast_ptr points to the last node. At this point the slow_ptr will be pointing to the nth node from the end. Insert the new node after this node. This method requires single traversal of the list.
Implementation:
C++
// C++ implementation to insert a node after the
// nth node from the end
#include <bits/stdc++.h>
using namespace std;
// structure of a node
struct Node {
int data;
Node* next;
};
// function to get a new node
Node* getNode(int data)
{
// allocate memory for the node
Node* newNode = (Node*)malloc(sizeof(Node));
// put in the data
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// function to insert a node after the
// nth node from the end
void insertAfterNthNode(Node* head, int n, int x)
{
// if list is empty
if (head == NULL)
return;
// get a new node for the value 'x'
Node* newNode = getNode(x);
// Initializing the slow and fast pointers
Node* slow_ptr = head;
Node* fast_ptr = head;
// move 'fast_ptr' to point to the nth node
// from the beginning
for (int i = 1; i <= n - 1; i++)
fast_ptr = fast_ptr->next;
// iterate until 'fast_ptr' points to the
// last node
while (fast_ptr->next != NULL) {
// move both the pointers to the
// respective next nodes
slow_ptr = slow_ptr->next;
fast_ptr = fast_ptr->next;
}
// insert the 'newNode' by making the
// necessary adjustment in the links
newNode->next = slow_ptr->next;
slow_ptr->next = newNode;
}
// function to print the list
void printList(Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program to test above
int main()
{
// Creating list 1->3->4->5
Node* head = getNode(1);
head->next = getNode(3);
head->next->next = getNode(4);
head->next->next->next = getNode(5);
int n = 4, x = 2;
cout << "Original Linked List: ";
printList(head);
insertAfterNthNode(head, n, x);
cout << "\nLinked List After Insertion: ";
printList(head);
return 0;
}
Java
// Java implementation to
// insert a node after the
// nth node from the end
class GfG
{
// structure of a node
static class Node
{
int data;
Node next;
}
// function to get a new node
static Node getNode(int data)
{
// allocate memory for the node
Node newNode = new Node();
// put in the data
newNode.data = data;
newNode.next = null;
return newNode;
}
// function to insert a node after
// the nth node from the end
static void insertAfterNthNode(Node head,
int n, int x)
{
// if list is empty
if (head == null)
return;
// get a new node for the value 'x'
Node newNode = getNode(x);
// Initializing the slow
// and fast pointers
Node slow_ptr = head;
Node fast_ptr = head;
// move 'fast_ptr' to point to the
// nth node from the beginning
for (int i = 1; i <= n - 1; i++)
fast_ptr = fast_ptr.next;
// iterate until 'fast_ptr' points
// to the last node
while (fast_ptr.next != null)
{
// move both the pointers to the
// respective next nodes
slow_ptr = slow_ptr.next;
fast_ptr = fast_ptr.next;
}
// insert the 'newNode' by making the
// necessary adjustment in the links
newNode.next = slow_ptr.next;
slow_ptr.next = newNode;
}
// function to print the list
static void printList(Node head)
{
while (head != null)
{
System.out.print(head.data + " ");
head = head.next;
}
}
// Driver code
public static void main(String[] args)
{
// Creating list 1->3->4->5
Node head = getNode(1);
head.next = getNode(3);
head.next.next = getNode(4);
head.next.next.next = getNode(5);
int n = 4, x = 2;
System.out.println("Original Linked List: ");
printList(head);
insertAfterNthNode(head, n, x);
System.out.println();
System.out.println("Linked List After Insertion: ");
printList(head);
}
}
// This code is contributed by
// Prerna Saini.
Python3
# Python3 implementation to insert a
# node after the nth node from the end
# Structure of a node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to get a new node
def getNode(data):
# Allocate memory for the node
newNode = Node(data)
return newNode
# Function to insert a node after the
# nth node from the end
def insertAfterNthNode(head, n, x):
# If list is empty
if (head == None):
return
# Get a new node for the value 'x'
newNode = getNode(x)
# Initializing the slow and fast pointers
slow_ptr = head
fast_ptr = head
# Move 'fast_ptr' to point to the nth
# node from the beginning
for i in range(1, n):
fast_ptr = fast_ptr.next
# Iterate until 'fast_ptr' points to the
# last node
while (fast_ptr.next != None):
# Move both the pointers to the
# respective next nodes
slow_ptr = slow_ptr.next
fast_ptr = fast_ptr.next
# Insert the 'newNode' by making the
# necessary adjustment in the links
newNode.next = slow_ptr.next
slow_ptr.next = newNode
# Function to print the list
def printList(head):
while (head != None):
print(head.data, end = ' ')
head = head.next
# Driver code
if __name__=='__main__':
# Creating list 1.3.4.5
head = getNode(1)
head.next = getNode(3)
head.next.next = getNode(4)
head.next.next.next = getNode(5)
n = 4
x = 2
print("Original Linked List: ", end = '')
printList(head)
insertAfterNthNode(head, n, x)
print("\nLinked List After Insertion: ", end = '')
printList(head)
# This code is contributed by rutvik_56
C#
// C# implementation to
// insert a node after the
// nth node from the end
using System;
class GfG
{
// structure of a node
public class Node
{
public int data;
public Node next;
}
// function to get a new node
static Node getNode(int data)
{
// allocate memory for the node
Node newNode = new Node();
// put in the data
newNode.data = data;
newNode.next = null;
return newNode;
}
// function to insert a node after
// the nth node from the end
static void insertAfterNthNode(Node head,
int n, int x)
{
// if list is empty
if (head == null)
return;
// get a new node for the value 'x'
Node newNode = getNode(x);
// Initializing the slow
// and fast pointers
Node slow_ptr = head;
Node fast_ptr = head;
// move 'fast_ptr' to point to the
// nth node from the beginning
for (int i = 1; i <= n - 1; i++)
fast_ptr = fast_ptr.next;
// iterate until 'fast_ptr' points
// to the last node
while (fast_ptr.next != null)
{
// move both the pointers to the
// respective next nodes
slow_ptr = slow_ptr.next;
fast_ptr = fast_ptr.next;
}
// insert the 'newNode' by making the
// necessary adjustment in the links
newNode.next = slow_ptr.next;
slow_ptr.next = newNode;
}
// function to print the list
static void printList(Node head)
{
while (head != null)
{
Console.Write(head.data + " ");
head = head.next;
}
}
// Driver code
public static void Main()
{
// Creating list 1->3->4->5
Node head = getNode(1);
head.next = getNode(3);
head.next.next = getNode(4);
head.next.next.next = getNode(5);
int n = 4, x = 2;
Console.WriteLine("Original Linked List: ");
printList(head);
insertAfterNthNode(head, n, x);
Console.WriteLine();
Console.WriteLine("Linked List After Insertion: ");
printList(head);
}
}
/* This code contributed by PrinciRaj1992 */
JavaScript
<script>
// JavaScript implementation to
// insert a node after the
// nth node from the end
// structure of a node
class Node {
constructor() {
this.data = 0;
this.next = null;
}
}
// function to get a new node
function getNode(data) {
// allocate memory for the node
var newNode = new Node();
// put in the data
newNode.data = data;
newNode.next = null;
return newNode;
}
// function to insert a node after
// the nth node from the end
function insertAfterNthNode(head, n, x) {
// if list is empty
if (head == null) return;
// get a new node for the value 'x'
var newNode = getNode(x);
// Initializing the slow
// and fast pointers
var slow_ptr = head;
var fast_ptr = head;
// move 'fast_ptr' to point to the
// nth node from the beginning
for (var i = 1; i <= n - 1; i++)
fast_ptr = fast_ptr.next;
// iterate until 'fast_ptr' points
// to the last node
while (fast_ptr.next != null) {
// move both the pointers to the
// respective next nodes
slow_ptr = slow_ptr.next;
fast_ptr = fast_ptr.next;
}
// insert the 'newNode' by making the
// necessary adjustment in the links
newNode.next = slow_ptr.next;
slow_ptr.next = newNode;
}
// function to print the list
function printList(head) {
while (head != null) {
document.write(head.data + " ");
head = head.next;
}
}
// Driver code
// Creating list 1->3->4->5
var head = getNode(1);
head.next = getNode(3);
head.next.next = getNode(4);
head.next.next.next = getNode(5);
var n = 4,
x = 2;
document.write("Original Linked List: ");
printList(head);
insertAfterNthNode(head, n, x);
document.write("<br>");
document.write("Linked List After Insertion:");
printList(head);
</script>
OutputOriginal Linked List: 1 3 4 5
Linked List After Insertion: 1 2 3 4 5
Time Complexity: O(n), where n is the number of nodes in the list.
Auxiliary Space: O(1)
Method 3 (Recursive Approach):
- Traverse the list recursively till we reach the last node.
- while back tracking insert the node at desired position.
Implementation:
C++
// C++ implementation to insert a node after the
// nth node from the end
#include <bits/stdc++.h>
using namespace std;
// structure of a node
struct Node {
int data;
Node* next;
};
// function to get a new node
Node* getNode(int data)
{
// allocate memory for the node
Node* newNode = new Node();
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// function to insert a node after the
// nth node from the end
void insertAfterNthNode(Node* head, int x, int& n)
{
// Base case
if (head == NULL)
return;
// recursively traverse till the last node
insertAfterNthNode(head->next, x, n);
// condition to insert the node after nth node from end
if (--n == 0) {
// create a node with the given value
Node* temp = getNode(x);
// update the next pointer to point next node in the
// list
temp->next = head->next;
// make sure head points to newly inserted node
head->next = temp;
}
}
// function to print the list
void printList(Node* head)
{
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Driver program to test above functions
int main()
{
// Creating list 1->3->4->5
Node* head = getNode(1);
head->next = getNode(3);
head->next->next = getNode(4);
head->next->next->next = getNode(5);
int n = 4, x = 2;
cout << "Original Linked List: ";
printList(head);
insertAfterNthNode(head, x, n);
cout << "\nLinked List After Insertion: ";
printList(head);
return 0;
}
// This code is contributed by Upendra
Java
// Java implementation to insert a node after the
// nth node from the end
class GfG {
// structure of a node
static class Node {
int data;
Node next;
}
// function to get a new node
static Node getNode(int data)
{
// allocate memory for the node
Node newNode = new Node();
// put in the data
newNode.data = data;
newNode.next = null;
return newNode;
}
static int n;
// function to insert a node after the
// nth node from the end
static void insertAfterNthNode(Node head, int x)
{
// Base case
if (head == null)
return;
// recursively traverse till the last node
insertAfterNthNode(head.next, x);
// condition to insert the node after nth node from
// end
if (--n == 0) {
// create a node with the given value
Node temp = getNode(x);
// update the next pointer to point next node in
// the list
temp.next = head.next;
// make sure head points to newly inserted node
head.next = temp;
}
}
// function to print the list
static void printList(Node head)
{
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
}
// Driver code
public static void main(String[] args)
{
// Creating list 1->3->4->5
Node head = getNode(1);
head.next = getNode(3);
head.next.next = getNode(4);
head.next.next.next = getNode(5);
n = 4;
int x = 2;
System.out.println("Original Linked List: ");
printList(head);
insertAfterNthNode(head, x);
System.out.println();
System.out.println("Linked List After Insertion: ");
printList(head);
}
}
// This code is contributed by Abhijeet Kumar(abhijeet19403)
Python3
# Python implementation to insert a node after the
# nth node from the end
class Node:
def __init__(self,data):
self.data = data
self.next = None
# function to get a new node
def getNode(data):
newNode = Node(data)
return newNode
# function to insert a node after the
# nth node from the end
def insertAfterNthNode(head,x,n):
# Base Case
if head == None:
return n-1
# recursively traverse till the last node
n = insertAfterNthNode(head.next,x,n)
# condition to insert the node after nth node from end
if n == 0:
# create a node with the given value
temp = getNode(x)
# update the next pointer to point next node in the list
temp.next = head.next
# make sure head points to newly inserted node
head.next = temp
return n-1
# function to print the list
def printList(head):
while head != None:
print(head.data,end = ' ')
head = head.next
print()
# Driver program to test above functions
# Creating list 1->3->4->5
head = getNode(1)
head.next = getNode(3)
head.next.next = getNode(4)
head.next.next.next = getNode(5)
n = 4
x = 2
print("Original Linked List: ")
printList(head)
insertAfterNthNode(head, x, n)
print("Linked List After Insertion: ")
printList(head)
C#
// C# implementation to insert a node after the
// nth node from the end
using System;
public class GFG {
// structure of a node
class Node {
public int data;
public Node next;
}
// function to get a new node
static Node getNode(int data)
{
// allocate memory for the node
Node newNode = new Node();
// put in the data
newNode.data = data;
newNode.next = null;
return newNode;
}
static int n;
// function to insert a node after the
// nth node from the end
static void insertAfterNthNode(Node head, int x)
{
// Base case
if (head == null)
return;
// recursively traverse till the last node
insertAfterNthNode(head.next, x);
// condition to insert the node after nth node from
// end
if (--n == 0) {
// create a node with the given value
Node temp = getNode(x);
// update the next pointer to point next node in
// the list
temp.next = head.next;
// make sure head points to newly inserted node
head.next = temp;
}
}
// function to print the list
static void printList(Node head)
{
while (head != null) {
Console.Write(head.data + " ");
head = head.next;
}
}
static public void Main()
{
// Code
// Creating list 1->3->4->5
Node head = getNode(1);
head.next = getNode(3);
head.next.next = getNode(4);
head.next.next.next = getNode(5);
n = 4;
int x = 2;
Console.Write("Original Linked List: ");
printList(head);
insertAfterNthNode(head, x);
Console.WriteLine();
Console.Write("Linked List After Insertion: ");
printList(head);
}
}
// This code is contributed by lokesh.
JavaScript
// JavaScript implementation to insert a node after the
// nth node from the end
// structure of a node
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
let n;
// function to insert a node after the
// nth node from the end
function insertAfterNthNode(head, x) {
// base case
if (head == null) return;
// recursively traverse till the last node
insertAfterNthNode(head.next, x);
// condition to insert the node after nth node from end
if (--n == 0) {
// create a node with the given value
let temp = new Node(x);
// update the next pointer to point to the next node in the list
temp.next = head.next;
// make sure head points to the newly inserted node
head.next = temp;
}
}
// function to print the list
function printList(head) {
let current = head;
while (current != null) {
console.log(current.data + " ");
current = current.next;
}
console.log("<br>");
}
// create a linked list: 1 -> 3 -> 4 -> 5
let head = new Node(1);
head.next = new Node(3);
head.next.next = new Node(4);
head.next.next.next = new Node(5);
n = 4;
let x = 2;
console.log("Original Linked List: ");
printList(head);
insertAfterNthNode(head, x);
console.log("\nLinked List After Insertion: ");
printList(head);
// This code is contributed by lokeshmvs21.
OutputOriginal Linked List: 1 3 4 5
Linked List After Insertion: 1 2 3 4 5
Time Complexity: O(n)
Where n is the number of nodes in the list.
Auxiliary Space: O(n)
Due to recursion call stack.
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