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

Spread the post

Print a linked list in to alternate first and last elements

Write an efficient algorithm to print a linked list in to alternate first and last elements.

For example.

Suppose linked list contain following nodes [1,2,3,4,5,6,7].

root_ptr7654321

Output : 1 7 2 6 3 5 4

View nodes

Stack Areamainroot(pointer)status (int) =1tail(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)= NULL

Program to print alternate first and last elements. Time complexity O(n).

Output

View process.

Stack Areamainroot(pointer)status (int) =1tail(pointer)print_nodehead(pointer)status(pointer)tail(pointer)print_nodehead(pointer)status(pointer)tail(pointer)print_nodehead(pointer)status(pointer)tail(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)= NULL

View steps of execution

Submit your solution in comment section.

Spread the post

Recommended Posts: