Spread the post

Move last n node at beginning of linked list

Write an efficient algorithm to move given last n nodes at beginning of linked list without using recursion.

For example given linked list are contain following nodes.

root_ptr12345678

Result

Function are move n-last node.

View pointers and nodes of Linked list.

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

After Move 5 last node.

root_ptr12345678

Note that change node link.

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

Try it Yourself

Program to move n last node at beginning of linked list. Time complexity O(n).


Output

View process

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

Try it Yourself

Spread the post

Recommended Posts: