Delete middle element of a linked list


Today we will discuss how to delete middle element of a linked list. But before moving to the solution you should be familiar with the concept of linked list.

 Procedure


First we will make a linked list.
Then we will count the number of nodes in a linked list.
Now we will have 2 cases -
1.) when the number of nodes are even then we will have 2 middle elements (n/2 and n/2+1).
2.) when the number of nodes are odd then we will have 1 middle element ((n+1)/2).
Then we will write the underlying code to delete middle element by analyzing if the number of nodes are even or odd.

Algorithm


We will first write a simple code which will have 2 functions:

1. insert() - which will insert elements to linked list.
2. show() - to display the linked list.

Now we will make a function deletemiddle() which will delete the middle element.
In the deletemiddle() we will make 1 node temp1 which will initially point to head of the linked list.
Then we will count the number of nodes in the linked list by traversing the list with temp1 and storing the count values in a count variable.
Now again we will initialize temp1 to head.
Now we will check count%2 == 0 (even) or count%2!=0 (odd).

If count%2==0 or number of nodes are even then:
1. We will find mid by count/2.
2. We will make a variable p of int type which will tell us if we have reached the desired node or not.
3. Now we will traverse the list. We will increment p with each iteration and also check if p+1 == mid or not.
4. If p+1 == mid that means the next node is then first middle node and the next node is the second middle node.
5. So we will use (temp1->next=temp1->next->next->next) which means to put the address of the node after the second middle element in the current node.

Delete middle element of a linked list


If count%2!=0 or number of nodes are odd then:
1. We will find mid by count/2.
2. We will make a variable p of int type which will tell us if we have reached the desired node or not.
3. Now we will traverse the list. We will increment p with each iteration and also check if p+1 == mid or not.
4. If p+1 == mid that means the next node is then middle node .
5. 5. So we will use (temp1->next=temp1->next->next) which means to put the address of the node after the middle element in the current node.


Delete middle element of a linked list


Implementation in C++


If you have any doubts then please ask in the comment section below.

Post a Comment (0)
Previous Post Next Post