Merge two sorted linked lists

Data Structures and Algorithms Note

Allie Hsu
Coder Life
2 min readJan 19, 2022

--

how I would do

Always draw for linked list questions then you will find the solution flow.

First of all, we create a dummy node in order to store the result, compare the first node between L1 and L2, let the smaller one be the dummy node.next, so that we know the new linked list starts from the dummy node.next and after finish combines two linked list, we could return the new linked list head by calling dummy node.next.

Compare the rest nodes of two linked lists one by one, link the smaller one to the new linked list and pointer go to the next node of that link, looping the action until one of them reached the last node. Then the other linked list, which hasn’t reached the end and still has some nodes, could be connected directly behind the new linked list.

Time Complexity: O(m+n)

--

--

Allie Hsu
Coder Life

A tech enthusiast who is keen to develop new skills