Merge two sorted linked list in golang

Sourav Patnaik
2 min readJan 21, 2021

Here I described how to merge two sorted linked list in golang. In this blog I have mentioned how to sort a linked list in golang.

copyright to sourav patnaik
image copyright to sourav patnaik

We will pass two sorted linked list to a function to merge and return us the merged list. In this blog, list = double linked list, created by “container/list” package.

Logic is very simple. We will create two pointers which points to the HEAD of the original list. Then by comparing the node values, we will write them to the resultMergedList one by one and increment the pointers to point the next node. If two lists have different length then we will add the remaining elements of the longer list to the resultMergedList.

merge two sorted linked list in golang

You can find the full code here .

Below is the code to call mergeSortedLinkedList

The output from line number 37, 39 :

after merging two sorted list, mergedList:
1
4
5
8
10
10
12
13
15

For more examples, follow here.

--

--