Delete middle of linked list

Introduction

The linked list is one of the most important concepts and data structures to learn while preparing for interviews. Proper understanding of concepts based on Linked Lists can give you an edge in a coding interview.

Problem Statement

In this problem, we are given a linked list, and we have to delete the middle element of the linked list.

Problem Statement Understanding

Let’s understand the problem statement with help of an example.

Let’s say the given linked list is:

Now we have to delete the middle element of the linked list such that the resultant linked list after deletion will look like this:

Explanation: 3rd node from the linked list has been removed, as it was the middle node of the linked list.

So let’s first think in terms of linked list, what deleting a node means.
Taking the above linked list, 5→10→15→20→25 as an example.

So here if we delete the node(10) we get:

So by deleting the node(10) we are making the connection between node(5) and node(15).

Observations for deletion

  • If we take some more examples, we will notice that we need the access of the previous and the next node of the node that we wish to delete.

Say, if the deleted node is the target, and its previous node is prev and its next node is next1. So, to do the deletion of the target node from the linked list, we need to do the following operations:

  • prev→next = next1
  • And finally free the target node

Similarly, in this problem we need to first find the position of the middle node and node previous to the middle node and then following the above-mentioned steps of deletion we have to delete the middle element.

So now we will see how to get the middle node and which node will be the middle node of linked list in case of even length and odd length linked list.

Observations for the position of the middle element
Even Length Linked List:

  • If there are an even number of nodes in the linked list, there will be two middle nodes, and the second middle node is the one which will get deleted if we want to delete the middle node of the linked list.
  • For example, if the given linked list is 5→10→15→20→25→30, then 15 and 20 will be the two middle nodes of the linked list, and we will remove the second middle node which is 20.
  • So our final modified linked list after deletion will be 5→10→15→25→30.

Odd Length Linked List:

  • If there are an odd number of nodes in the linked list, there will be a single middle node, and we will delete that node from the linked list.
  • For example, if the given linked list is 5→10→15→20→25, then 15 will be the middle node of the linked list, and we will remove this node from the linked list.
  • So our final modified linked list after deletion will be 5→10→20→30.

Note: If there is just one node present in the input linked list, that node should be removed and a new head should be returned.

Approach 1

The concept is to count the number of nodes N in a linked list first, then delete the (N/2)th node using the simple deletion method.

The (N/2)th node which we will delete will be the middle node of the linked list.

Algorithm 1

  • If head is NULL, return NULL.
  • If next of head is NULL, delete head and return NULL.
  • Create a node Head_copy and make it point to the head.
  • Initialize a counter variable count = 0, and now with help of head, traverse the linked list incrementing the count variable by 1 for each node of the linked list.
  • Finally, when the traversal of the list will be over count will contain the count of number of nodes in the linked list.
  • The position of the middle node of the linked list will be given by (count/2), store it in a variable mid.
  • Now starting from the head of the linked list, traverse until the below condition holds:
    while (mid-- > 1) {
    head = head→next;
    }
  • At the end of the while loop, you will be at the node previous of the middle node. So now make head→next = head→next→next to delete the middle node of the linked list.
  • Finally, return Head_copy, which is the head of the newly formed list.

Code Implementation

// Program to delete middle element of a linked list
#include 
using namespace std;

// Node in a linked list
struct Node {
    int val;
    struct Node* next;
};

// counting the number of nodes present in the list
int count_nodes(struct Node* head)
{
    int n_count = 0;
    while (head != NULL) {
        head = head->next;
        n_count++;
    }
    return n_count;
}

// returns head of the newly formed list
// after deleting the middle element.
struct Node* delete_middle(struct Node* head)
{
    if (head == NULL)
        return NULL;
    if (head->next == NULL) {
        delete head;
        return NULL;
    }
    struct Node* Head_copy = head;

    // total nodes currently there in the list
    int count = count_nodes(head);

    // position of middle element in the list
    int mid = count / 2;

    // Delete the middle node
    while (mid-- > 1) {
        head = head->next;
    }

    // Delete the middle node
    head->next = head->next->next;

    return Head_copy;
}

// Function to display the list
void display_List(struct Node* x)
{
    while (x != NULL) {
        cout << x->val << "->";
        x = x->next;
    }
    // Last element points to null
    cout << "NULL\n";
}

// function to create a new node.
Node* newNode(int value)
{
    struct Node* t = new Node;
    t->val = value;
    t->next = NULL;
    return t;
}

// Driver Function
int main()
{
    // Adding elements to the empty list
    struct Node* head = newNode(5);
    head->next = newNode(10);
    head->next->next = newNode(15);
    head->next->next->next = newNode(20);
     head->next->next->next->next = newNode(25);

    cout << "Original List" << endl;
    display_List(head);

    head = delete_middle(head);

    cout << "List after deleting the middle element"
 << endl;
    display_List(head);

    return 0;
}

Output

Original List
5→10→15→20→25→NULL
List after deleting the middle element
5→10→20→25→NULL

Time Complexity: O(n), only a single traversal of the linked list is required.
Space Complexity: O(1), No extra space is needed.

In the above Approach 1, we are traversing the linked list twice:

  • First traversal to find the length of the linked list
  • Then, in the second traversal, moving up to (length/2)th node of the linked list and deleting it.

The first question which we should ask ourselves is that do we actually need to find the length of the linked list to delete the middle node of the linked list?
The answer is No, we don’t need to find the length of the linked list to delete the middle node of the linked list.

Approach 2

Now in this approach we will try to find the middle of the linked list in one traversal. We will see how can we tackle this:

  • What if we start by taking two pointers, say slow and fast, and make both of them point to head initially.
  • Now what will happen if we make slow jump one place and fast jump two place (fast moving with twice as speed as slow).
  • If we notice carefully by doing the above steps, we will see that when the fast will reach the end of the list, the slow will be pointing to the middle of the list.
  • With help of this technique, we can reach the middle of the linked list in one single pass, and hence our objective of reaching the middle of the linked list and deleting it will be achieved in one single traversal of the list.

The reason why slow will be pointing to the middle of the linked list when fast reaches the end is that, as our slow pointer is travelling with half of the speed of the fast pointer, so when fast pointer will reach the end of the linked list, till that time slow pointer will have travelled only half the distance as travelled by fast pointer and hence it will be at middle of the linked list.

So in this way, using slow and fast pointers, we can find the position of the middle element of the linked list and then using its previous node we can delete the middle node of the linked list.

Algorithm 2

  • Create two pointers, slow and fast.
  • We will also create a temporary pointer prev which will keep track of the previous node of the slow pointer.
  • Initially, both slow and fast will be pointing to the head of the linked list.
  • Now make slow pointer jump one place and fast pointer jump two places, until fast pointer reaches the end of the list.
  • When the fast pointer reaches the end, the slow pointer will be pointing to the middle of the linked list.
  • Now using the prev pointer which is keeping track of previous node to the node pointed by slow pointer, remove the node pointed by slow from the linked list by performing the below operations:
    1) prev→next = slow->next
    2) delete(slow)
  • Finally, the middle node has been deleted from the linked list.

Dry Run

Code Implementation

// Program to delete middle element of a linked list
#include 
using namespace std;

// Node in a linked list
struct Node {
    int val;
    struct Node* next;
};

// returns head of the newly formed list
// after deleting the middle element.
struct Node* delete_middle(struct Node* head)
{
    if (head == NULL)
        return NULL;
    if (head->next == NULL) {
        delete head;
        return NULL;
    }
    
        // Inorder to reach the middle element,
// Initializing slow and fast pointers
    struct Node* slow = head;
    struct Node* fast = head;
     
        // Finding out the middle as well as
// previous of middle.
// Store previous of slow   
struct Node* prev;
    while (fast != NULL && fast->next != NULL) {
        fast = fast->next->next;
        prev = slow;
        slow = slow->next;
    }
 
    // Now, delete the middle element
    prev->next = slow->next;
    delete slow;
 
    return head;

}

// Function to display the list
void display_List(struct Node* x)
{
    while (x != NULL) {
        cout << x->val << "->";
        x = x->next;
    }
    // Last element points to null
    cout << "NULL\n";
}

// function to create a new node.
Node* newNode(int value)
{
    struct Node* t = new Node;
    t->val = value;
    t->next = NULL;
    return t;
}

// Driver Function
int main()
{
    // Adding elements to the empty list
    struct Node* head = newNode(5);
    head->next = newNode(10);
    head->next->next = newNode(15);
    head->next->next->next = newNode(20);
     head->next->next->next->next = newNode(25);

    cout << "Original List" << endl;
    display_List(head);

    head = delete_middle(head);

    cout << "List after deleting the middle element"
 << endl;
    display_List(head);

    return 0;
}

Output

Original List
5→10→15→20→25→NULL
List after deleting the middle element
5→10→20→25→NULL

Time Complexity: O(n), only a single traversal of the linked list is required.

In this article, we have tried to explain the algorithm for deleting the middle element in the linked list. This problem is interesting as well as important from the interview’s point of view. If you want to solve more questions on Linked List, which are curated by our expert mentors at PrepBytes, you can follow this link Linked List.

Previous post Partitioning a linked list around a given value and keeping the original order
Next post Rotate Doubly linked list by N nodes

Leave a Reply

Your email address will not be published. Required fields are marked *