导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-21.Merge Two Sorted Lists

题目

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.

翻译

将两个已排序链表混合并返回一个新的链表。新的链表应该由前两个链表黏接而成。

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;

ListNode head = new ListNode(0), tmp = head;
while (true) {
if (l1.val < l2.val) {
tmp.val = l1.val;
l1 = l1.next;
} else if (l1.val > l2.val) {
tmp.val = l2.val;
l2 = l2.next;
} else {
tmp.val = l1.val;
tmp.next = new ListNode(l2.val);
tmp = tmp.next;
l1 = l1.next;
l2 = l2.next;
}
if (l1 == null || l2 == null)
break;
tmp.next = new ListNode(0);
tmp = tmp.next;
}

while (l1 != null) {
tmp.next = new ListNode(l1.val);
tmp = tmp.next;
l1 = l1.next;
}
while (l2 != null) {
tmp.next = new ListNode(l2.val);
tmp = tmp.next;
l2 = l2.next;
}

return head;
}
}

后来突然发现题中要求用原链表的节点黏接而成,修改算法如下:

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
32
33
34
35
36
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;

ListNode head = new ListNode(0), tmp = head;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
tmp.next = l1;
l1 = l1.next;
} else {
tmp.next = l2;
l2 = l2.next;
}
tmp = tmp.next;
}

if (l1 != null)
tmp.next = l1;

if (l2 != null)
tmp.next = l2;

return head.next;
}
}

参考:
http://www.programcreek.com/2012/12/leetcode-merge-two-sorted-lists-java/