C++ Program For Inserting A Node After The N-th Node From The End
Last Updated :
14 Aug, 2022
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.
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 << "
Linked List After Insertion: ";
printList(head);
return 0;
}
Output:
Original 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.
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 << "
Linked List After Insertion: ";
printList(head);
return 0;
}
Output:
Original 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) because using constant variables
Please refer complete article on Insert a node after the n-th node from the end for more details!
Similar Reads
C++ Program For Inserting Node In The Middle Of The Linked List Given a linked list containing n nodes. The problem is to insert a new node with data x at the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node. Examples: Input : list: 1->2->4->5 x = 3 Output : 1->2->
5 min read
C++ Program For Printing Nth Node From The End Of A Linked List Given a Linked List and a number n, write a function that returns the value at the n'th node from the end of the Linked List.For example, if the input is below list and n = 3, then output is "B" Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Method 1 (Use length
4 min read
C++ Program For Inserting A Node In A Linked List Inserting a node into a linked list can be done in several ways, depending on where we want to insert the new node. Here, we'll cover four common scenarios: inserting at the front of the list, after a given node, at a specific position, and at the end of the listTable of ContentInsert a Node at the
9 min read
C++ Program To Delete N Nodes After M Nodes Of A Linked List Given a linked list and two integers M and N. Traverse the linked list such that you retain M nodes then delete next N nodes, continue the same till end of the linked list.Difficulty Level: Rookie Examples: Input: M = 2, N = 2 Linked List: 1->2->3->4->5->6->7->8 Output: Linked L
3 min read
C++ Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc
5 min read
C++ Program For Writing A Function To Get Nth Node In A Linked List Write a C++ Program to GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1->10->30->14, index = 2Output: 30 The node at index 2 is 30Recommended: Please solve it on "PRACTICE" first, before m
4 min read
C++ Program To Find The Sum Of Last N Nodes Of The Given Linked List Given a linked list and a number n. Find the sum of the last n nodes of the linked list.Constraints: 0 <= n <= number of nodes in the linked list. Examples: Input: 10->6->8->4->12, n = 2 Output: 16 Sum of last two nodes: 12 + 4 = 16 Input: 15->7->9->5->16->14, n = 4
10 min read
C++ Program For Moving Last Element To Front Of A Given Linked List Write a function that moves the last element to the front in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4. Algorithm: Traverse the list till the last node. Use two pointers: one t
3 min read
C++ Program For Insertion Sort In A Singly Linked List We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list. 2) Traverse the given list, do following for every node. ......a) Insert curr
5 min read
C++ Program For Making Middle Node Head In A Linked List Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list. Examples: Input: 1 2 3 4 5 Output: 3 1 2 4 5 Input: 1 2 3 4 5 6 Output: 4 1 2 3 5 6 The idea is to first find middle of a linked list using two pointers, first one moves
3 min read