I have an integer linked list of which both first half and second half are sorted independently.Now i need to merge two parts to create one single sorted linked list.
Sample input:
Input List 1: 1->2->3->4->5->1->2
Output : 1->1->2->2->3->4->5
Input List 2: 1->5->7->9->11->2->4->6
Output 2: 1->2->4->5->6->7->9->11
Expected output:
1,2,3…..
This is merge sort.
I will maintain two pointers:
ptr1points to the first half’s first elementand
ptr2points to the second half’s first element.you will need an extra array to store the final list, of course you can choose not to use this extra array, but that discussion is far away from the topic.
1, Compare
*ptr1and*ptr2, if*ptr1‘s value is smaller than*ptr2, then copy that value(i.e.*ptr1) to the final array, and letptr1move forward.if
ptr2‘s value is the smaller one, just copy*ptr2and letptr2move forward2, Stop when the pointer points after the last element, say if you have 5 elements in the first half
a[0] a[1] a[2] a[3] a[4], then you should stop when the pointer points toa[5]3, If the first half is empty, then copy the rest of the second half, vice versa.