Learn basic concept of c , c++ and python programming in regularcodes.com

Spread the post

Delete middle element of linked list

Delete node at middle of linked list. here described all test case to delete middle of linked list.

case 1: if only one element of linked list. then delete that node and assign root pointer to NULL value.

case 2: if linked list contain more then one number of nodes. then find (n/2) middle node and delete this node. example linked list contain following data 51-->63-->21-->52-->51-->51-->23--->NULL. view linked list in below.

If you need to view insertion of this linked list. then visit below link..

Try it Yourself

note that there number of linked list nodes are Odd. that means easily to find that middle node and also delete.

Process to delete middle of linked list Process to delete this middle element 51 root_ptr help_ptr temp_ptr 235151 52 21 6351

before remove middle element find previous node in this case help_ptr are pointed to previous of middle node. modification help_ptr next point value and remove middle element.

After remove middle element of linked list.

After delete middle element 51 After delete middle of linked list root_ptr 235151216351

case 3: suppose linked list have Even number of nodes. for example again delete middle node of previous linked list once again.

Before delete linked list Before delete middle element linked list is root_ptr 2351 51 216351

in this case boths node [ 21, 51] are same priority to delete. either delete node 21 or 51.

After delete middle element 21 After delete middle of linked list root_ptr 2351516351

Note that here deleted given first middle node 21. You can also delete second middle.

Delete node using this algorithm:

Time complexity of this algorithm is O(n).

Accepted Output of given linked list

Execution Process To delete middle of linked list

Delete middle of linked list this execution process are visualize how to delete mid node of linked list. Stack Areamainroot(pointer)remove_mid_elementfind_element(pointer)help(pointer)temp(pointer) Heap Areastruct Nodedata (int)= 51next (pointer) struct Nodedata (int)= 63next (pointer) struct Nodedata (int)= 21next (pointer) struct Nodedata (int)= 52next (pointer) struct Nodedata (int)= 51next (pointer) struct Nodedata (int)= 51next (pointer) struct Nodedata (int)= 23next (pointer)= NULL

In this execution process not imagination all steps. below link click and view how to insert linked list node, how to show all linked list node and delete middle element of node.

Try it Yourself

Given C program to delete middle of linked list

 ---------> Case Odd Nodes <---------

Before remove : 
51  63  21  52  51  51  23  

After remove :
 51  63  21  51  51  23  
---------> Case Even Nodes <---------

Before remove : 
51  63  21  51  51  23  

After remove :
 51  63  51  51  23  

 Free linked list Node element 

Spread the post

Recommended Posts: