Delete middle of linked list in C++ program

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn how to delete the middle node in a linked list.

The solution to the problem is straightforward. We will have two pointers one moves one node at a time and the other one moves two nodes at a time. By the time the second pointer reaches the final node, the first will be in the middle of the linked list.

Let's see the steps to solve the problem.

  • Write a struct Node for the linked list node.

  • Initialize the linked list with the dummy data.

  • Write a function to delete the linked list.

    • Initialize two-pointers (slow and fast) with linked list head pointer.

    • Iterate over the linked list until the fast pointer reaches the end.

    • Move the slow pointer to one next node.

    • Move the fast pointer to the next node of the next node.

    • Return the head pointer

  • Print the linked list.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
struct Node* deleteMiddleNode(struct Node* head) {
   if (head == NULL) {
      return NULL;
   }
   if (head->next == NULL) {
      delete head;
      return NULL;
   }
   struct Node* slow_ptr = head;
   struct Node* fast_ptr = head;
   struct Node* prev;
   while (fast_ptr != NULL && fast_ptr->next != NULL) {
      fast_ptr = fast_ptr->next->next;
      prev = slow_ptr;
      slow_ptr = slow_ptr->next;
   }
   prev->next = slow_ptr->next;
   delete slow_ptr;
   return head;
}
void printLinkedList(struct Node* node) {
   while (node != NULL) {
      cout << node->data << " -> ";
      node = node->next;
   }
   cout << "Null" << endl;
}
Node* newNode(int data) {
   struct Node* temp = new Node;
   temp->data = data;
   temp->next = NULL;
   return temp;
}
int main() {
   struct 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);
   head->next->next->next->next->next = newNode(6);
   cout << "Linked list before deleting middle node: ";
   printLinkedList(head);
   head = deleteMiddleNode(head);
   cout << "Linked List after deleting middle node: ";
   printLinkedList(head);
   return 0;
}

Output

If you execute the above program, then you will get the following result.

Linked list before deleting middle node: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> Null
Linked List after deleting middle node: 1 -> 2 -> 3 -> 5 -> 6 -> Null

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 27-Jan-2021 12:06:38
Advertisements