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

Spread the post

Move middle N node in end of linked list

Suppose linked list contain following nodes [ 10, 20, 30, 40, 50, 60, 70, 80 ,90, 100 ]. Our goal is to Move middle N nodes in end of linked list.

Test Case

The following cases are follow of this problem.

Case 1 : first and last node are not a part of middle nodes. Example linked list contain 3 nodes [1,2,3]. and there are only one middle [2]. if user are given to move 2 middle node to end of linked list then it is not possible.

Case 2 : if two set of middle node then move first set of end of linked list. example [1,2,3,4,5] if move 2 middle nodes. then possible to sets A [2,3] and B[3,4]. in this case move first set.

root_ptr100908070605040302010

Try it Yourself

View pointers and nodes.

Stack Areamainmove_node (int) ? root(pointer) Heap Areastruct Nodedata (int)= 10next (pointer) struct Nodedata (int)= 20next (pointer) struct Nodedata (int)= 30next (pointer) struct Nodedata (int)= 40next (pointer) struct Nodedata (int)= 50next (pointer) struct Nodedata (int)= 60next (pointer) struct Nodedata (int)= 70next (pointer) struct Nodedata (int)= 80next (pointer) struct Nodedata (int)= 90next (pointer) struct Nodedata (int)= 100next (pointer)= NULL

Try it Yourself

Example 1: Move middle 6 nodes.

root_ptr100908070605040302010

After move middle 6 nodes.

root_ptr807060504030100902010

Visualize process.

Stack Areamainmove_node (int) =6root(pointer)move_n_nodescount (int) =-1helper(pointer)middle_node(pointer)root(pointer)size (int) =0temp(pointer) Heap Areastruct Nodedata (int)= 10next (pointer) struct Nodedata (int)= 20next (pointer) struct Nodedata (int)= 30next (pointer) struct Nodedata (int)= 40next (pointer) struct Nodedata (int)= 50next (pointer) struct Nodedata (int)= 60next (pointer) struct Nodedata (int)= 70next (pointer) struct Nodedata (int)= 80next (pointer) struct Nodedata (int)= 90next (pointer) struct Nodedata (int)= 100next (pointer)

Try it Yourself

C program to Move Middle N nodes at End of linked list . Iterative approach.


Output

Spread the post

Recommended Posts: