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

Spread the post

Merge two sorted linked lists in sorted form

Suppose linked list L1 contain following nodes [2 4 7 9 11 ] and L2 contain following nodes [1 2 3 5 8 14 17 ].Our goal is to Merge two sorted linked lists in sorted form.

Example

Linked list L1.

root1119742

Try it Yourself

Linked list L2.

root2171485321

Try it Yourself

View pointers and nodes.

Stack Areamainroot1(pointer)root2(pointer)root3(pointer) NULL Heap Areastruct Nodedata (int)= 2next (pointer) struct Nodedata (int)= 4next (pointer) struct Nodedata (int)= 7next (pointer) struct Nodedata (int)= 9next (pointer) struct Nodedata (int)= 11next (pointer)= NULLstruct Nodedata (int)= 1next (pointer) struct Nodedata (int)= 2next (pointer) struct Nodedata (int)= 3next (pointer) struct Nodedata (int)= 5next (pointer) struct Nodedata (int)= 8next (pointer) struct Nodedata (int)= 14next (pointer) struct Nodedata (int)= 17next (pointer)= NULL

Try it Yourself

Function to merge two linked list.

After Merge Linked list L3 is.

root_ptr171411987543221

Process to merge linked list.

Stack Areamainroot1(pointer) NULLroot2(pointer) NULLroot3(pointer)show_datatemp (pointer) ? Heap Areastruct Nodedata (int)= 2next (pointer) struct Nodedata (int)= 4next (pointer) struct Nodedata (int)= 7next (pointer) struct Nodedata (int)= 9next (pointer) struct Nodedata (int)= 11next (pointer) struct Nodedata (int)= 1next (pointer) struct Nodedata (int)= 2next (pointer) struct Nodedata (int)= 3next (pointer) struct Nodedata (int)= 5next (pointer) struct Nodedata (int)= 8next (pointer) struct Nodedata (int)= 14next (pointer) struct Nodedata (int)= 17next (pointer)= NULL

Try it Yourself

C program to Merge two sorted linked list. Iterative approach time complexity O(n).


Output

Spread the post

Recommended Posts: