[Naive Approach] Using Two-Pass Traversal - O(n) Time and O(1) space
The basic to first traverse the entire linked list to count the total number of nodes. Once we know the total number of nodes, we can calculate the position of the middle node, which is at index n/2 (where n is the total number of nodes). Then go through the linked list again, but this time we stop right before the middle node. Once there, we modify the next pointer of the node before the middle node so that it skips over the middle node and points directly to the node after it,
C++
// C++ program to delete middle of a linked list#include<bits/stdc++.h>usingnamespacestd;structNode{intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to delete middle node from linked list.Node*deleteMid(Node*head){// Edge case: return nullptr if there is only// one node.if(head->next==nullptr)returnnullptr;intcount=0;Node*p1=head,*p2=head;// First pass, count the number of nodes// in the linked list using 'p1'.while(p1!=nullptr){count++;p1=p1->next;}// Get the index of the node to be deleted.intmiddleIndex=count/2;// Second pass, let 'p2' move toward the predecessor// of the middle node.for(inti=0;i<middleIndex-1;++i)p2=p2->next;// Delete the middle node and return 'head'.Node*temp=p2->next;p2->next=temp->next;deletetemp;returnhead;}voidprintList(Node*head){Node*temp=head;while(temp!=nullptr){cout<<temp->data<<" -> ";temp=temp->next;}cout<<"nullptr"<<endl;}intmain(){// Create a static hardcoded linked list:// 1 -> 2 -> 3 -> 4 -> 5.Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);cout<<"Original Linked List: ";printList(head);// Delete the middle node.head=deleteMid(head);cout<<"Linked List after deleting the middle node: ";printList(head);return0;}
C
// C program to delete middle of a linked list#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};// Function to delete middle node from linked list.structNode*deleteMid(structNode*head){// Edge case: return NULL if there is only// one node.if(head->next==NULL)returnNULL;intcount=0;structNode*p1=head,*p2=head;// First pass, count the number of nodes// in the linked list using 'p1'.while(p1!=NULL){count++;p1=p1->next;}// Get the index of the node to be deleted.intmiddleIndex=count/2;// Second pass, let 'p2' move toward the predecessor// of the middle node.for(inti=0;i<middleIndex-1;++i)p2=p2->next;// Delete the middle node and return 'head'.structNode*temp=p2->next;p2->next=temp->next;free(temp);returnhead;}voidprintList(structNode*head){structNode*temp=head;while(temp!=NULL){printf("%d -> ",temp->data);temp=temp->next;}printf("NULL\n");}structNode*newNode(intx){structNode*temp=(structNode*)malloc(sizeof(structNode));temp->data=x;temp->next=NULL;returntemp;}intmain(){// Create a static hardcoded linked list:// 1 -> 2 -> 3 -> 4 -> 5.structNode*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);printf("Original Linked List: ");printList(head);// Delete the middle node.head=deleteMid(head);printf("Linked List after deleting the middle node: ");printList(head);return0;}
Java
// Java program to delete middle of a linked listclassNode{intdata;Nodenext;Node(intx){data=x;next=null;}}publicclassGfG{// Function to delete middle node from linked list.publicstaticNodedeleteMid(Nodehead){// Edge case: return null if there is only// one node.if(head.next==null)returnnull;intcount=0;Nodep1=head,p2=head;// First pass, count the number of nodes// in the linked list using 'p1'.while(p1!=null){count++;p1=p1.next;}// Get the index of the node to be deleted.intmiddleIndex=count/2;// Second pass, let 'p2' move toward predecessor// of the middle node.for(inti=0;i<middleIndex-1;++i)p2=p2.next;// Delete the middle node and return 'head'.p2.next=p2.next.next;returnhead;}publicstaticvoidprintList(Nodehead){Nodetemp=head;while(temp!=null){System.out.print(temp.data+" -> ");temp=temp.next;}System.out.println("null");}publicstaticvoidmain(String[]args){// Create a static hardcoded linked list:// 1 -> 2 -> 3 -> 4 -> 5.Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);System.out.print("Original Linked List: ");printList(head);// Delete the middle node.head=deleteMid(head);System.out.print("Linked List after deleting the middle node: ");printList(head);}}
Python
# Python3 program to delete middle of a linked listclassNode:def__init__(self,data):self.data=dataself.next=None# Function to delete middle node from linked list.defdeleteMid(head):# Edge case: return None if there is only# one node.ifhead.nextisNone:returnNonecount=0p1=headp2=head# First pass, count the number of nodes# in the linked list using 'p1'.whilep1isnotNone:count+=1p1=p1.next# Get the index of the node to be deleted.middleIndex=count//2# Second pass, let 'p2' move toward the predecessor# of the middle node.foriinrange(middleIndex-1):p2=p2.next# Delete the middle node and return 'head'.p2.next=p2.next.nextreturnheaddefprintList(head):temp=headwhiletempisnotNone:print(temp.data,end=" -> ")temp=temp.nextprint("None")if__name__=="__main__":# Create a static hardcoded linked list:# 1 -> 2 -> 3 -> 4 -> 5.head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)print("Original Linked List:",end=" ")printList(head)# Delete the middle node.head=deleteMid(head)print("Linked List after deleting the middle node:",end=" ")printList(head)
C#
// C# program to delete middle of a linked listusingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to delete middle node from linked list.staticNodedeleteMid(Nodehead){// Edge case: return null if there is only// one node.if(head.next==null)returnnull;intcount=0;Nodep1=head,p2=head;// First pass, count the number of nodes// in the linked list using 'p1'.while(p1!=null){count++;p1=p1.next;}// Get the index of the node to be deleted.intmiddleIndex=count/2;// Second pass, let 'p2' move toward the predecessor// of the middle node.for(inti=0;i<middleIndex-1;++i)p2=p2.next;// Delete the middle node and return 'head'.p2.next=p2.next.next;returnhead;}staticvoidprintList(Nodehead){Nodetemp=head;while(temp!=null){Console.Write(temp.data+" -> ");temp=temp.next;}Console.WriteLine("null");}staticvoidMain(string[]args){// Create a static hardcoded linked list:// 1 -> 2 -> 3 -> 4 -> 5.Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);Console.Write("Original Linked List: ");printList(head);// Delete the middle node.head=deleteMid(head);Console.Write("Linked List after deleting the middle node: ");printList(head);}}
JavaScript
classNode{constructor(data){this.data=data;this.next=null;}}// Function to delete middle node from linked list.functiondeleteMid(head){// Edge case: return null if there is only// one node.if(head.next===null)returnnull;letcount=0;letp1=head,p2=head;// First pass, count the number of nodes// in the linked list using 'p1'.while(p1!==null){count++;p1=p1.next;}// Get the index of the node to be deleted.letmiddleIndex=Math.floor(count/2);// Second pass, let 'p2' move toward the predecessor// of the middle node.for(leti=0;i<middleIndex-1;++i)p2=p2.next;// Delete the middle node and return 'head'.p2.next=p2.next.next;returnhead;}functionprintList(head){lettemp=head;while(temp!==null){console.log(temp.data+" -> ");temp=temp.next;}console.log("null");}// Create a static hardcoded linked list:// 1 -> 2 -> 3 -> 4 -> 5.lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);console.log("Original Linked List: ");printList(head);// Delete the middle node.head=deleteMid(head);console.log("Linked List after deleting the middle node: ");printList(head);
Output
Original Linked List: 1 -> 2 -> 3 -> 4 -> 5 -> nullptr
Linked List after deleting the middle node: 1 -> 2 -> 4 -> 5 -> nullptr
Time Complexity: O(n). Two traversals of the linked list are needed Auxiliary Space: O(1). No extra space is needed.
[Expected Approach] One-Pass Traversal with Slow and Fast Pointers - O(n) Time and O(1) Space
The above solution requires two traversals of the linked list. The middle node can be deleted using one traversal. The idea is to use two pointers, slow_ptr, and fast_ptr. The fast pointer moves two nodes at a time, while the slow pointer moves one node at a time. When the fast pointer reaches the end of the list, the slow pointer will be positioned at the middle node. Next, you need to connect the node that comes before the middle node (prev) to the node that comes after the middle node. This effectively skips over the middle node, removing it from the list.
C++
// C++ program to delete middle of a linked list#include<bits/stdc++.h>usingnamespacestd;structNode{intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to delete middle node from linked liststructNode*deleteMid(structNode*head){// If the list is empty, return NULLif(head==NULL)returnNULL;// If the list has only one node,// delete it and return NULLif(head->next==NULL){deletehead;returnNULL;}structNode*prev=NULL;structNode*slow_ptr=head;structNode*fast_ptr=head;// Move the fast pointer 2 nodes ahead// and the slow pointer 1 node ahead// until fast pointer reaches end of the listwhile(fast_ptr!=NULL&&fast_ptr->next!=NULL){fast_ptr=fast_ptr->next->next;// Update prev to hold the previous // slow pointer valueprev=slow_ptr;slow_ptr=slow_ptr->next;}// At this point, slow_ptr points to middle node// Bypass the middle nodeprev->next=slow_ptr->next;// Delete the middle nodedeleteslow_ptr;// Return the head of the modified listreturnhead;}voidprintList(structNode*head){structNode*temp=head;while(temp!=NULL){cout<<temp->data<<" -> ";temp=temp->next;}cout<<"NULL"<<endl;}intmain(){// Create a static hardcoded linked list:// 1 -> 2 -> 3 -> 4 -> 5Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);cout<<"Original Linked List: ";printList(head);// Delete the middle nodehead=deleteMid(head);cout<<"Linked List after deleting the middle node: ";printList(head);return0;}
C
// C program to delete middle of a linked list#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};// Function to delete middle node from linked liststructNode*deleteMid(structNode*head){// If the list is empty, return NULLif(head==NULL)returnNULL;// If the list has only one node,// delete it and return NULLif(head->next==NULL){free(head);returnNULL;}structNode*prev=NULL;structNode*slow_ptr=head;structNode*fast_ptr=head;// Move the fast pointer 2 nodes ahead// and the slow pointer 1 node ahead// until fast pointer reaches end of the listwhile(fast_ptr!=NULL&&fast_ptr->next!=NULL){fast_ptr=fast_ptr->next->next;// Update prev to hold the previous // slow pointer valueprev=slow_ptr;slow_ptr=slow_ptr->next;}// At this point, slow_ptr points to middle node// Bypass the middle nodeprev->next=slow_ptr->next;// Delete the middle nodefree(slow_ptr);// Return the head of the modified listreturnhead;}voidprintList(structNode*head){structNode*temp=head;while(temp!=NULL){printf("%d -> ",temp->data);temp=temp->next;}printf("NULL\n");}structNode*newNode(intx){structNode*temp=(structNode*)malloc(sizeof(structNode));temp->data=x;temp->next=NULL;returntemp;}intmain(){// Create a static hardcoded linked list:// 1 -> 2 -> 3 -> 4 -> 5.structNode*head=newNode(1);head->next=newNode(2);head->next->next=newNode(3);head->next->next->next=newNode(4);head->next->next->next->next=newNode(5);printf("Original Linked List: ");printList(head);// Delete the middle node.head=deleteMid(head);printf("Linked List after deleting the middle node: ");printList(head);return0;}
Java
// Java program to delete the middle of a linked listclassNode{intdata;Nodenext;Node(intx){data=x;next=null;}}classGfG{// Function to delete middle node from linked liststaticNodedeleteMid(Nodehead){// If the list is empty, return nullif(head==null)returnnull;// If the list has only one node,// delete it and return nullif(head.next==null){returnnull;}Nodeprev=null;Nodeslow_ptr=head;Nodefast_ptr=head;// Move the fast pointer 2 nodes ahead// and the slow pointer 1 node ahead// until fast pointer reaches end of listwhile(fast_ptr!=null&&fast_ptr.next!=null){fast_ptr=fast_ptr.next.next;// Update prev to hold the previous // slow pointer valueprev=slow_ptr;slow_ptr=slow_ptr.next;}// At this point,slow_ptr points to middle node// Bypass the middle nodeprev.next=slow_ptr.next;// Return the head of the modified listreturnhead;}staticvoidprintList(Nodehead){Nodetemp=head;while(temp!=null){System.out.print(temp.data+" -> ");temp=temp.next;}System.out.println("NULL");}publicstaticvoidmain(String[]args){// Create a static hardcoded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);System.out.print("Original Linked List: ");printList(head);// Delete the middle nodehead=deleteMid(head);System.out.print("Linked List after deleting the middle node: ");printList(head);}}
Python
# Python program to delete the middle of a linked listclassNode:def__init__(self,data):self.data=dataself.next=None# Function to delete middle node from linked listdefdeleteMid(head):# If the list is empty, return NoneifheadisNone:returnNone# If the list has only one node,# delete it and return Noneifhead.nextisNone:returnNoneprev=Noneslow_ptr=headfast_ptr=head# Move the fast pointer 2 nodes ahead# and the slow pointer 1 node ahead# until fast pointer reaches end of the listwhilefast_ptrisnotNoneandfast_ptr.nextisnotNone:fast_ptr=fast_ptr.next.next# Update prev to hold the previous# slow pointer valueprev=slow_ptrslow_ptr=slow_ptr.next# At this point, slow_ptr points to middle node# Bypass the middle nodeprev.next=slow_ptr.next# Return the head of the modified listreturnheaddefprintList(head):temp=headwhiletemp:print(temp.data,end=" -> ")temp=temp.nextprint("NULL")if__name__=="__main__":# Create a static hardcoded linked list:# 1 -> 2 -> 3 -> 4 -> 5head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)head.next.next.next.next=Node(5)print("Original Linked List: ",end="")printList(head)# Delete the middle nodehead=deleteMid(head)print("Linked List after deleting the middle node: ",end="")printList(head)
C#
// C# program to delete middle of a linked listusingSystem;classNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGfG{// Function to delete middle node from linked listpublicstaticNodedeleteMid(Nodehead){// If the list is empty, return nullif(head==null)returnnull;// If the list has only one node,// delete it and return nullif(head.next==null){returnnull;}Nodeprev=null;Nodeslow_ptr=head;Nodefast_ptr=head;// Move the fast pointer 2 nodes ahead// and the slow pointer 1 node ahead// until fast pointer reaches end of the listwhile(fast_ptr!=null&&fast_ptr.next!=null){fast_ptr=fast_ptr.next.next;// Update prev to hold the previous // slow pointer valueprev=slow_ptr;slow_ptr=slow_ptr.next;}// At this point, slow_ptr points to middle node// Bypass the middle nodeprev.next=slow_ptr.next;// Return the head of the modified listreturnhead;}// Function to print the linked listpublicstaticvoidprintList(Nodehead){Nodetemp=head;while(temp!=null){Console.Write(temp.data+" -> ");temp=temp.next;}Console.WriteLine("NULL");}publicstaticvoidMain(string[]args){// Create a static hardcoded linked list:// 1 -> 2 -> 3 -> 4 -> 5Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);Console.Write("Original Linked List: ");printList(head);// Delete the middle nodehead=deleteMid(head);Console.Write("Linked List after deleting the middle node: ");printList(head);}}
JavaScript
// javascript program to delete middle of a linked listclassNode{constructor(data){this.data=data;this.next=null;}}// Function to delete the middle node from the linked listfunctiondeleteMid(head){// If the list is empty, return nullif(head===null){returnnull;}// If the list has only one node, delete it and return// nullif(head.next===null){returnnull;}letprev=null;letslow_ptr=head;letfast_ptr=head;// Move the fast pointer 2 nodes ahead// and the slow pointer 1 node ahead// until the fast pointer reaches the end of the listwhile(fast_ptr!==null&&fast_ptr.next!==null){fast_ptr=fast_ptr.next.next;// Update prev to hold the previous slow pointer// valueprev=slow_ptr;slow_ptr=slow_ptr.next;}// At this point, slow_ptr points to the middle node// Bypass the middle nodeprev.next=slow_ptr.next;// Return the head of the modified listreturnhead;}functionprintList(head){lettemp=head;while(temp!==null){process.stdout.write(temp.data+" -> ");temp=temp.next;}console.log("null");}// Create a static hardcoded linked list:// 1 -> 2 -> 3 -> 4 -> 5lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);head.next.next.next.next=newNode(5);process.stdout.write("Original Linked List: ");printList(head);// Delete the middle nodehead=deleteMid(head);process.stdout.write("Linked List after deleting the middle node: ");printList(head);
Output
Original Linked List: 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Linked List after deleting the middle node: 1 -> 2 -> 4 -> 5 -> NULL
Time Complexity: O(n). Only one traversal of the linked list is needed Auxiliary Space: O(1). As no extra space is needed.