merge two sorted linked list code example
Example 1: merge two sorted lists python
from heapq import merge
# initializing lists
test_list1 = [1, 5, 6, 9, 11]
test_list2 = [3, 4, 7, 8, 10]
# printing original lists
print ("The original list 1 is : " + str(test_list1))
print ("The original list 2 is : " + str(test_list2))
# using heapq.merge()
# to combine two sorted lists
res = list(merge(test_list1, test_list2))
# printing result
print ("The combined sorted list is : " + str(res))
Example 2: merge sort in linked list
Merge_Sort(head_reference)
STEP 1: If head is NULL or there is only one element in the Linked List
then return the Linked List
STEP 2: Divide the linked list into two equal halves.
Split_Linked_List(head, &first_half, &second_half);
STEP 3: Sort the two halves first_half and second_half.
MergeSort(first_half);
MergeSort(second_half);
STEP 4: Merge the sorted first_half and second_half (using Merge_Sort() recursively)
and update the head pointer using head_reference.
*head_reference = Merge_Sort(first_half, second_half);
Example 3: merge two sorted list in python
# l1 and l2 are lists
sorted(l1+l2)