leetcode [#21]

目录

题目

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 && l2 == null) {
return null;
} else if(l1 == null) {
return l2;
} else if(l2 == null){
return l1;
}

ListNode h1 = l1;
ListNode h2 = l2;
ListNode result = new ListNode(0);
ListNode cur = result;

while(h1 != null || h2 != null){
if(h1 != null && h2 != null){
if(h1.val <= h2.val){
cur.val = h1.val;
h1 = h1.next;
} else {
cur.val = h2.val;
h2 = h2.next;
}
} else if(h1 == null) {
cur.val = h2.val;
h2 = h2.next;
} else {
cur.val = h1.val;
h1 = h1.next;
}
if(h1 == null && h2 == null){
cur.next = null;
break;
} else {
cur.next = new ListNode(0);
cur = cur.next;
}
}
return result;
}
}

注意事项

  1. 从结果来看,题目默认的是升序排序。
  2. 两个有序链表合并,可以看到归并排序算法的影子,按照归并排序的算法进行处理即可。