Star

LeetCode 21. Merge Two Sorted Lists

Question

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Explanation

两个指针。非常简单。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode a = l1;
ListNode b = l2;
if (l1 == null && l2 == null) return null;
ListNode curr = new ListNode(0);
ListNode dummy= curr;
while(a != null && b != null) {
if (a.val < b.val) {
dummy.next = new ListNode(a.val);
a = a.next;
} else {
dummy.next = new ListNode(b.val);
b = b.next;
}
dummy = dummy.next;
}
if(a!= null) dummy.next = a;
else dummy.next = b;
return curr.next;
}
}