Sort Linked List in golang

Sourav Patnaik
2 min readJan 20, 2021

Golang provides “container/list” package using which we can implement double linked list. In interview, they generally ask to write a program to sort a linked list. Here I will create a double linked list using “container/list” package and will sort.

creating a double linked list

list. New() returns an initialized list. I am adding integer to the list. list accepts interface{}. so you can add any valid type values here.

PushBack() is like adding elements one after one.

PushFront() will add element to the beginning of the list.

to iterate over a list, follow the for loop.

now the output is:

node1: &{{0xc000072360 0xc0000723f0 <nil> <nil>} 4}
node2: &{{0xc0000724e0 0xc000072510 <nil> <nil>} 5}
1
5
10
13
15

Now we will write a function to sort the list.

sort linked list

sortLinkedList() function will sort the list that is passed as an argument and will return the sorted list.

we are passing list as a pointer, so any changes made to the list by this function will reflect to the caller.

You can add more validations checks in this function.

Below is the code to call sort function and print the sorted list.

calling sort function

You can find the full code here.

after calling sort function, final output:

after sort, node1:
4
8
10
12
after sort, node2:
1
5
10
13
15

follow more examples on https://github.com/sourav977

--

--