p21

LeetCode 21 Merge Two Sorted Lists 题解

1.题目:

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.

题意:

合并两个有序链表

2.解题思路:

见代码。记得保留头节点。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 

public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode ans = new ListNode(0);
;
ListNode node = ans;

while (l1 != null && l2 != null) {
if (l1.val >= l2.val) {
node.next = l2;

l2 = l2.next;
} else {
node.next = l1;
l1 = l1.next;
}
// System.out.println(node.val);
node = node.next;
}
node.next = (l1 != null) ? l1 : l2;

return ans.next;//因为是用0初始化的,去掉初始的节点
}
}

4.一些总结:输入测试数据的时候,不要让你的链表变成一个环。