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

Spread the post

Move first node a middle of given linked list

Suppose following data [1, 2, 3, 4, 5, 6, 7, 8] are inserted on linked list.


Try it yourself

Following process to move first node at middle of linked list.

1) Use two pointer temp and helper. temp pointer and helper pointer are pointing to first node of linked list.

root_ptr87654321 temp,helper

2) First find middle node of linked list.

root_ptr87654321 helper temp

3) move root pointer to second node of linked list.


root_ptr87654321 helper temp

4) helper=temp->next;

First node of linked list that (next pointer) value are pointed to middle node of next node pointer.

root_ptr87654321 helper temp

5) temp->next=helper;

And finally middle node pointed to next node of this helper pointer.

root_ptr87654321 helper temp


Time complexity of this algorithm O(n).

Code Execution:

Stack Areamainroot(pointer)move_nodehelper(pointer)root(pointer)temp(pointer) Heap Areastruct Nodedata (int)= 1next (pointer) struct Nodedata (int)= 2next (pointer) struct Nodedata (int)= 3next (pointer) struct Nodedata (int)= 4next (pointer) struct Nodedata (int)= 5next (pointer) struct Nodedata (int)= 6next (pointer) struct Nodedata (int)= 7next (pointer) struct Nodedata (int)= 8next (pointer)= NULL

Note that not given all step of execution process here.View How to insert linked list element, how to print and so on.

Try it yourself

c program to move first node at middle of linked list.

 Case 1: Empty Linked list 
  Empty linked List

 case 2: When linked list are not empty 
 Before move linked list :1  2  3  4  5  6  7  8  
 After move linked list :2  3  4  1  5  6  7  8  

 Free nodes of linked linked 

Spread the post

Recommended Posts: