1. Topic
Merges two ascending lists into a new ascending list and returns. The new linked list is formed by splicing all the nodes of the given two linked lists.
Example 1:
Input : l1 = [1,2,4], l2 = [1,3,4]
Output : [1,1,2,3,4,4]
Example 2:
Input : l1 = [], l2 = []
Output : []
Example 3:
Input : l1 = [], l2 = [0]
Output : [0]
Link to the topic: https://leetcode.cn/problems/merge-two-sorted-lists
2. Diagram
Suppose our linked lists are:
l1 = [1,2,4]
l2 = [1,3,4]
At the same time, we set a "prehead" sentinel node, which is roughly as follows:
First we maintain a prehead sentinel node . We actually just need to adjust its next pointer . ** Make it always point to the smaller of l1 or l2 until either l1 or l2 points to null. **In this way, at the end, if there are remaining elements in l1 or l2 that are not used, then the remaining elements must be larger than the linked list that prehead has merged (because it is an ordered linked list) . We only need to append all these elements to the linked list merged by prehead, and finally get the linked list we need. The approximate process is as follows:
- First we point the prehead to the smaller of l1 or l2. Either will do if they are equal. At this time, l1 is [2,4], and l2 is [1,3,4]
- We continue with the steps above. Point the prehead's linked list to the smaller of l1 and l2. Right now it's pointing to 1.
- Repeat the above steps.
- Now prehead.Next is the linked list we need.
3. Java sample code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode(0), p = dummy;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
p.next = list1;
list1 = list1.next;
} else {
p.next = list2;
list2 = list2.next;
}
p = p.next;
}
if (list1 != null) p.next = list1;
if (list2 != null) p.next = list2;
return dummy.next;
}
}
Results of the: