Given a linked list containing n nodes. The problem is to insert a new node with data x in 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: head = 1->2->4 , x = 3 Output: 1->2->3->4
Input: head = 10->20->40->50 , x = 30 Output: 10->20->30->40->50 Explanation: The new element is inserted after the current middle element in the linked list and Hence, the output is 10->20->30->40->50.
The idea is to first find the length of linked list and then insert node with value x after the half length of the linked list.
C++
// C++ implementation to insert node at the middle// of the linked list#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to insert a node at the middle// of the linked listNode*insertInMiddle(Node*head,intx){// If the list is emptyif(head==nullptr){returnnewNode(x);}Node*newNode=newNode(x);Node*currNode=head;intlen=0;// Calculate the length of the linked listwhile(currNode!=nullptr){len++;currNode=currNode->next;}// Calculate the position to insert the new nodeintmid;if(len%2==0){mid=len/2;}else{mid=(len+1)/2;}currNode=head;// Move to the position before where// the new node will be insertedwhile(mid>1){currNode=currNode->next;mid--;}// Insert the new node and adjust the linksnewNode->next=currNode->next;currNode->next=newNode;returnhead;}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->next;}cout<<endl;}intmain(){// Creating the list 1->2->4->5Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(4);head->next->next->next=newNode(5);intx=3;head=insertInMiddle(head,x);printList(head);return0;}
C
// C implementation to insert node at the middle// of the linked list#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intx);// Function to insert a node at the middle // of the linked liststructNode*insertInMiddle(structNode*head,intx){if(head==NULL){returncreateNode(x);}structNode*newNode=createNode(x);structNode*currNode=head;intlen=0;// Calculate the length of the linked listwhile(currNode!=NULL){len++;currNode=currNode->next;}intmid=(len%2==0)?len/2:(len+1)/2;currNode=head;// Move to the position before// where the new node will be insertedwhile(mid>1){currNode=currNode->next;mid--;}// Insert the new node and adjust the linksnewNode->next=currNode->next;currNode->next=newNode;returnhead;}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d ",curr->data);curr=curr->next;}printf("\n");}structNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->next=NULL;returnnewNode;}intmain(){// Creating the list 1->2->4->5structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(4);head->next->next->next=createNode(5);intx=3;head=insertInMiddle(head,x);printList(head);return0;}
Java
// Java implementation to insert node// at the middle of the linked listclassNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Function to insert a node at// the middle of the linked liststaticNodeinsertInMiddle(Nodehead,intx){if(head==null){returnnewNode(x);}NodenewNode=newNode(x);NodecurrNode=head;intlen=0;// Calculate the length of the linked listwhile(currNode!=null){len++;currNode=currNode.next;}// Determine the middle positionintcount=(len%2==0)?(len/2):(len+1)/2;currNode=head;// Traverse to the middle nodewhile(count-->1){currNode=currNode.next;}// Insert the new node in the middlenewNode.next=currNode.next;currNode.next=newNode;returnhead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// Creating the list 1->2->4->5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(4);head.next.next.next=newNode(5);intx=3;head=insertInMiddle(head,x);printList(head);}}
Python
# Python3 implementation to insert node# at the middle of a linked listclassNode:def__init__(self,data):self.data=dataself.next=None# Function to insert a node at the# middle of the linked listdefinsertInMiddle(head,x):ifheadisNone:returnNode(x)new_node=Node(x)curr_node=headlength=0# Calculate the length of the linked listwhilecurr_nodeisnotNone:length+=1curr_node=curr_node.nextmid=length//2iflength%2==0else(length+1)//2curr_node=head# Move to the position before# where the new node will be insertedwhilemid>1:curr_node=curr_node.nextmid-=1# Insert the new node and adjust the linksnew_node.next=curr_node.nextcurr_node.next=new_nodereturnheaddefprint_list(head):curr=headwhilecurrisnotNone:print(curr.data,end=" ")curr=curr.nextprint()if__name__=="__main__":# Creating the list 1->2->4->5head=Node(1)head.next=Node(2)head.next.next=Node(4)head.next.next.next=Node(5)x=3head=insertInMiddle(head,x)print_list(head)
C#
// C# implementation to insert node// at the middle of the linked listusingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to insert a node at the middle of the linked// liststaticNodeinsertInMiddle(Nodehead,intx){if(head==null){returnnewNode(x);}NodenewNode=newNode(x);NodecurrNode=head;intlen=0;// Calculate the length of the linked listwhile(currNode!=null){len++;currNode=currNode.next;}// Determine the middle positionintcount=(len%2==0)?(len/2):(len+1)/2;currNode=head;// Traverse to the middle nodewhile(count-->1){currNode=currNode.next;}// Insert the new node in the middlenewNode.next=currNode.next;currNode.next=newNode;returnhead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data+" ");curr=curr.next;}Console.WriteLine();}publicstaticvoidMain(string[]args){// Creating the list 1->2->4->5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(4);head.next.next.next=newNode(5);intx=3;head=insertInMiddle(head,x);printList(head);}}
JavaScript
// Javascript implementation to insert node// at the middle of the linked listclassNode{constructor(data){this.data=data;this.next=null;}}// Function to insert a node// at the middle of the linked listfunctioninsertInMiddle(head,x){if(head===null){returnnewNode(x);}letnewNode=newNode(x);letcurrNode=head;letlength=0;// Calculate the length of the linked listwhile(currNode!==null){length++;currNode=currNode.next;}letmid=(length%2===0)?length/2:(length+1)/2;currNode=head;// Move to the position before// where the new node will be insertedwhile(mid-->1){currNode=currNode.next;}// Insert the new node and adjust the linksnewNode.next=currNode.next;currNode.next=newNode;returnhead;}functionprintList(head){letcurr=head;while(curr!==null){process.stdout.write(curr.data+" ");curr=curr.next;}console.log();}// Creating the list 1->2->4->5lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(4);head.next.next.next=newNode(5);letx=3;head=insertInMiddle(head,x);printList(head);
Output
1 2 3 4 5
Using Single Traversal - O(n) Time and O(1) Space:
The idea is based on the tortoise and hare algorithm which uses two pointers, slow_ptr and fast_ptr to traverse the list. Here, slow_ptr moves one step at a time while fast moves two steps. When fast_ptr reaches the end or NULL then slow_ptr will point to the middle of the linked list. Now, we can insert the new node after slow_ptr..
C++
// C++ implementation to insert node at the middle// of the linked list#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to insert a node// at the middle of the linked listNode*insertInMiddle(Node*head,intx){// If the list is emptyif(head==nullptr){returnnewNode(x);}else{// Create a new nodeNode*newNode=newNode(x);// Assign values to the slow and fast pointersNode*slow=head;Node*fast=head->next;// Move slow and fast pointers to find the middlewhile(fast&&fast->next){slow=slow->next;fast=fast->next->next;}// Insert the newNode and adjust the linksnewNode->next=slow->next;slow->next=newNode;returnhead;}}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->next;}cout<<endl;}intmain(){// Creating the list 1->2->4->5Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(4);head->next->next->next=newNode(5);intx=3;head=insertInMiddle(head,x);printList(head);return0;}
C
// C implementation to insert node at the middle// of the linked list#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intx);// Function to insert a node// at the middle of the linked liststructNode*insertInMiddle(structNode*head,intx){// If the list is emptyif(head==NULL){returncreateNode(x);}else{// Create a new nodestructNode*newNode=createNode(x);// Assign values to the slow and fast pointersstructNode*slow=head;structNode*fast=head->next;// Move slow and fast pointers to find the middlewhile(fast&&fast->next){slow=slow->next;fast=fast->next->next;}// Insert the newNode and adjust the linksnewNode->next=slow->next;slow->next=newNode;returnhead;}}voidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d ",curr->data);curr=curr->next;}printf("\n");}structNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->next=NULL;returnnewNode;}intmain(){// Creating the list 1->2->4->5structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(4);head->next->next->next=createNode(5);intx=3;head=insertInMiddle(head,x);printList(head);return0;}
Java
// Java implementation to insert node// at the middle of the linked listclassNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Function to insert a node at the// middle of the linked liststaticNodeinsertInMiddle(Nodehead,intx){// If the list is empty, create a new node as the// headif(head==null){returnnewNode(x);}else{// Create a new nodeNodenewNode=newNode(x);Nodeslow=head;Nodefast=head.next;// Move slow and fast pointers to find the// middlewhile(fast!=null&&fast.next!=null){slow=slow.next;fast=fast.next.next;}// Insert the new node in the middlenewNode.next=slow.next;slow.next=newNode;returnhead;}}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.data+" ");curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// Creating the list 1->2->4->5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(4);head.next.next.next=newNode(5);intx=3;head=insertInMiddle(head,x);printList(head);}}
Python
# Python3 implementation to insert node# at the middle of a linked listclassNode:def__init__(self,data):self.data=dataself.next=None# Function to insert a node# at the middle of the linked listdefinsertInMiddle(head,x):# If the list is empty, create# a new node as the headifheadisNone:returnNode(x)else:# Create a new nodenew_node=Node(x)slow=headfast=head.next# Move slow and fast pointers to find the middlewhilefastandfast.next:slow=slow.nextfast=fast.next.next# Insert the new node in the middlenew_node.next=slow.nextslow.next=new_nodereturnheaddefprint_list(head):curr=headwhilecurrisnotNone:print(curr.data,end=" ")curr=curr.nextprint()if__name__=="__main__":# Creating the list 1->2->4->5head=Node(1)head.next=Node(2)head.next.next=Node(4)head.next.next.next=Node(5)x=3head=insertInMiddle(head,x)print_list(head)
C#
// C# implementation to insert node// at the middle of the linked listusingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to insert a node at the middle of the linked// liststaticNodeinsertInMiddle(Nodehead,intx){// If the list is empty, create a new node as the// headif(head==null){returnnewNode(x);}else{// Create a new nodeNodenewNode=newNode(x);Nodeslow=head;Nodefast=head.next;// Move slow and fast pointers to find the// middlewhile(fast!=null&&fast.next!=null){slow=slow.next;fast=fast.next.next;}// Insert the new node in the middlenewNode.next=slow.next;slow.next=newNode;returnhead;}}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.data+" ");curr=curr.next;}Console.WriteLine();}publicstaticvoidMain(string[]args){// Creating the list 1->2->4->5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(4);head.next.next.next=newNode(5);intx=3;head=insertInMiddle(head,x);printList(head);}}
JavaScript
// Javascript implementation to insert node// at the middle of the linked listclassNode{constructor(data){this.data=data;this.next=null;}}// Function to insert a node// at the middle of the linked listfunctioninsertInMiddle(head,x){// If the list is empty, create// a new node as the headif(head===null){returnnewNode(x);}else{// Create a new nodeletnewNode=newNode(x);letslow=head;letfast=head.next;// Move slow and fast pointers to find the middlewhile(fast!==null&&fast.next!==null){slow=slow.next;fast=fast.next.next;}// Insert the new node in the middlenewNode.next=slow.next;slow.next=newNode;returnhead;}}functionprintList(head){letcurrNode=head;while(currNode!==null){process.stdout.write(currNode.data+" ");currNode=currNode.next;}console.log();}lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(4);head.next.next.next=newNode(5);letx=3;head=insertInMiddle(head,x);printList(head);