Spread the post

Split a linked list into two halves

Split a linked list into two halves. suppose linked list contain following nodes[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

root_ptr10987654321

Try it Yourself

View pointers and nodes.

Stack Areamainback(pointer) NULLfront(pointer) NULLroot(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) struct Nodedata (int)= 9next (pointer) struct Nodedata (int)= 10next (pointer)= NULL

Try it Yourself

Example : Divide a linked list into two part.

First halves.

front54321

Back halves.

back109876

visualize execution process.

Stack Areamainback(pointer)front(pointer)root(pointer)split_two_halvesback(pointer)front(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)= NULLstruct Nodedata (int)= 6next (pointer) struct Nodedata (int)= 7next (pointer) struct Nodedata (int)= 8next (pointer) struct Nodedata (int)= 9next (pointer) struct Nodedata (int)= 10next (pointer)= NULL

Try it Yourself

Accepted Output

Note that if linked list are contain number of Odd nodes. then first half contain one extra node of second half halves.

C program to split a linked list into two halves. Iterative approach.


Output

Spread the post

Recommended Posts: