Python Program For Inserting Node In The Middle Of The Linked List
Last Updated :
19 Jul, 2022
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->3->4->5
Input : list: 5->10->4->32->16
x = 41
Output : 5->10->4->41->32->16
Method 1(Using length of the linked list):
Find the number of nodes or length of the linked using one traversal. Let it be len. Calculate c = (len/2), if len is even, else c = (len+1)/2, if len is odd. Traverse again the first c nodes and insert the new node after the cth node.
Python3
# Python3 implementation to insert node
# at the middle of a linked list
# Node class
class Node:
# constructor to create a new node
def __init__(self, data):
self.data = data
self.next = None
# function to insert node at the
# middle of linked list given the head
def insertAtMid(head, x):
if(head == None): #if the list is empty
head = Node(x)
else:
# create a new node for the value
# to be inserted
newNode = Node(x)
ptr = head
length = 0
# calculate the length of the linked
# list
while(ptr != None):
ptr = ptr.next
length += 1
# 'count' the number of node after which
# the new node has to be inserted
if(length % 2 == 0):
count = length / 2
else:
(length + 1) / 2
ptr = head
# move ptr to the node after which
# the new node has to inserted
while(count > 1):
count -= 1
ptr = ptr.next
# insert the 'newNode' and adjust
# links accordingly
newNode.next = ptr.next
ptr.next = newNode
# function to display the linked list
def display(head):
temp = head
while(temp != None):
print(str(temp.data), end = " ")
temp = temp.next
# Driver Code
# Creating the linked list 1.2.4.5
head = Node(1)
head.next = Node(2)
head.next.next = Node(4)
head.next.next.next = Node(5)
print("Linked list before insertion: ", end = "")
display(head)
# inserting 3 in the middle of the linked list.
x = 3
insertAtMid(head, x)
print("
Linked list after insertion: " , end = "")
display(head)
# This code is contributed by Pranav Devarakonda
Output:
Linked list before insertion: 1 2 4 5
Linked list after insertion: 1 2 3 4 5
Time Complexity: O(n)
Space complexity: O(n) where n is the number of nodes in a linked list
Method 2(Using two pointers):
Based on the tortoise and hare algorithm which uses two pointers, one known as slow and the other known as fast. This algorithm helps in finding the middle node of the linked list. It is explained in the front and black split procedure of this post. Now, you can insert the new node after the middle node obtained from the above process. This approach requires only a single traversal of the list.
Python3
# Python implementation to insert node
# at the middle of the linked list
# Node Class
class Node :
def __init__(self, d):
self.data = d
self.next = None
class LinkedList:
# function to insert node at the
# middle of the linked list
def __init__(self):
self.head = None
# Function to insert a new node
# at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def insertAtMid(self, x):
# if list is empty
if (self.head == None):
self.head = Node(x)
else:
# get a new node
newNode = Node(x)
# assign values to the slow
# and fast pointers
slow = self.head
fast = self.head.next
while (fast != None and
fast.next != None):
# move slow pointer to next node
slow = slow.next
# move fast pointer two nodes
# at a time
fast = fast.next.next
# insert the 'newNode' and
# adjust the required links
newNode.next = slow.next
slow.next = newNode
# function to display the linked list
def display(self):
temp = self.head
while (temp != None):
print(temp.data, end = " "),
temp = temp.next
# Driver Code
# Creating the list 1.2.4.5
ll = LinkedList()
ll.push(5)
ll.push(4)
ll.push(2)
ll.push(1)
print("Linked list before insertion: "),
ll.display()
x = 3
ll.insertAtMid(x)
print("
Linked list after insertion: "),
ll.display()
# This code is contributed by prerna saini
Output:
Linked list before insertion: 1 2 4 5
Linked list after insertion: 1 2 3 4 5
Time Complexity: O(n)
Space complexity: O(n) where n is size of linked list
Please refer complete article on Insert node into the middle of the linked list for more details!
Similar Reads
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 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 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 For Finding The Middle Element Of A Given Linked List Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list
4 min read
Python 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
Python Program To Delete Middle Of Linked List Given a singly linked list, delete the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the linked list should be modified to 1->2->4->5 If there are even nodes, then there would be two middle nodes, we need to delete the second middle element. For example, if g
4 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 Inserting A Node After The N-th Node From The End 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
7 min read
Python program to find middle of a linked list using one traversal Given a singly linked list, find the middle of the linked list. Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. Method 1: Traverse the whole linked list and count the no. of nodes. Now tra
5 min read
Python Program For Removing Middle Points From a Linked List Of Line Segments Given a linked list of coordinates where adjacent points either form a vertical line or a horizontal line. Delete points from the linked list which are in the middle of a horizontal or vertical line.Examples: Input: (0,10)->(1,10)->(5,10)->(7,10) | (7,5)->(20,5)->(40,5) Output: Linked
4 min read