21. Merge Two Sorted Lists
Question:
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
Input: l1 = [], l2 = []
Output: []
Input: l1 = [], l2 = [0]
Output: [0]
Source code
Version 1
Idea:
I haven't written a program with ListNode before. So, ListNode's constructor is very strange to me. I directly refered to Huahua's Tech Road.
The method used a temporary node as the start of the result list, named dummy. The ListNode pointer's tail always points to the last node in the result list, so you can use tail->next=l1
to append new Nodes easily.
Notice: Must to do tail=tail->next
to get next node' memory address.
The while() proceeds, it means two of ListNode aren't empty. It one of ListNodes is empty, non-empty ListNode is added value to tail. When the processing is done, the result is in dummy.next
(because the first value is 0, initial value).
1 | /** |