Merge two sorted linked lists.
Example 1:
Input:
a: 5->10->15, b: 2->3->20
Output: 2->3->5->10->15->20
Example 2:
Input: a: 1->1, b: 2->4
Output: 1->1->2->4
1. Structure Node:-
First, a structure Node is defined to represent linked list nodes. Each node has an integer key and a
pointer to the next node.
2. Function newNode:-
A function newNode(int key) is defined to create a new node with the given key value. It allocates memory
for the new node, sets the key, and initializes the next pointer to NULL.
3. Function newNode:-
In the main function, two sorted linked lists a and b are created. These linked lists are as follows:
List a: 5 -> 10 -> 15 -> 40
List b: 2 -> 3 -> 20
A vector v is declared to store the keys from both linked lists. This is done using two while loops:
The first loop iterates over list a and appends its keys to the vector v.
The second loop iterates over list b and appends its keys to the same vector v.
The vector v is then sorted in ascending order using the sort function from the C++ Standard Library.
4. merged sort:-
A new linked list is created to store the merged and sorted elements. A dummy node result is initially
created to simplify the code.
Using a for loop, the sorted values from the vector v are used to create new nodes and build the merged
linked list. The result pointer is moved to the next node with each iteration.
The temp pointer is used to keep track of the head of the merged linked list. It is set to the next node of
the dummy node result.
5. output:-
Finally, the code prints the elements of the merged linked list, displaying the result.