Python Program For Inserting A Node After The N-th Node From The End
Last Updated :
07 Apr, 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.
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
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) because using constant space
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.
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)
print()
insertAfterNthNode(head, n, x)
print("Linked List After Insertion: ", end = '')
printList(head)
# This code is contributed by rutvik_56
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) because using constant space
Please refer complete article on Insert a node after the n-th node from the end for more details!
Using two pointers:
Approach:
In this approach, we use two pointers, one that is n steps ahead of the other. Once the first pointer reaches the end of the list, the second pointer will be at the nth node from the end. We can then insert the new node after this node.
The Node class has two instance variables: data and next. data stores the value of the node, and next stores a reference to the next node in the list.
The LinkedList class has one instance variable: head. head stores a reference to the first node in the list.
The LinkedList class defines a method insert_after_nth_from_end that inserts a new node with the value x after the nth node from the end of the list.
The method first iterates through the list to count the number of nodes. If the count is less than n, the method returns without making any changes to the list. Otherwise, it iterates through the list again to find the nth node from the end.
It then creates a new node with the value x, inserts it after the nth node from the end, and updates the references of the surrounding nodes accordingly.
The LinkedList class also defines a method print_list that prints the values of all the nodes in the list, separated by spaces.
In the example code provided, a linked list is created with four nodes: 1 -> 3 -> 4 -> 5. The insert_after_nth_from_end method is then called with arguments 4 and 2, which means a new node with the value 2 should be inserted after the fourth node from the end of the list.
Python3
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert_after_nth_from_end(self, n, x):
temp = self.head
count = 0
while temp:
temp = temp.next
count += 1
if count < n:
return
temp = self.head
for i in range(count-n):
temp = temp.next
new_node = Node(x)
new_node.next = temp.next
temp.next = new_node
def print_list(self):
temp = self.head
while temp:
print(temp.data, end=' ')
temp = temp.next
print()
llist = LinkedList()
llist.head = Node(1)
second = Node(3)
third = Node(4)
fourth = Node(5)
llist.head.next = second
second.next = third
third.next = fourth
llist.insert_after_nth_from_end(4, 2)
llist.print_list()
Time complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Python 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->
4 min read
Python Program For Inserting A Node In A Linked List We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of linked list. Python # Node class class Node: # Function to initialize the # node o
7 min read
Python 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
Python 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
Python 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
Python 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
Python 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
Python Program To Delete Alternate Nodes Of A Linked List Given a Singly Linked List, starting from the second node delete all alternate nodes of it. For example, if the given linked list is 1->2->3->4->5 then your function should convert it to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3. Recomm
3 min read
Python Program for Deleting a Node in a Linked List We have discussed Linked List Introduction and Linked List Insertion in previous posts on a singly linked list.Let us formulate the problem statement to understand the deletion process. Given a 'key', delete the first occurrence of this key in the linked list. Iterative Method:To delete a node from
3 min read
Python Program For Moving All Occurrences Of An Element To End In A Linked List Given a linked list and a key in it, the task is to move all occurrences of the given key to the end of the linked list, keeping the order of all other elements the same. Examples: Input : 1 -> 2 -> 2 -> 4 -> 3 key = 2 Output : 1 -> 4 -> 3 -> 2 -> 2 Input : 6 -> 6 -> 7
6 min read