-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathMergeLinked17.java
More file actions
65 lines (58 loc) · 1.51 KB
/
MergeLinked17.java
File metadata and controls
65 lines (58 loc) · 1.51 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.so;
import com.so.Common.ListNode;
/**
* 第17题
* 输入两个递增的链表,合并这两个链表并使新链表仍然是递增的
*
* @author qgl
* @date 2017/08/10
*/
public class MergeLinked17 {
/**
* 解法一:递归
* 时间复杂度:O(m+n),空间复杂度:O(m+n)
*
* @param list1
* @param list2
* @return
*/
public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
if (list1.val < list2.val) {
list1.next = mergeTwoLists(list1.next, list2);
return list1;
} else {
list2.next = mergeTwoLists(list1, list2.next);
return list2;
}
}
/**
* 解法二:迭代
* 时间复杂度:O(m+n),空间复杂度:O(1)
*
* @param list1
* @param list2
* @return
*/
public static ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
ListNode preHead = new ListNode(-1);
ListNode pre = preHead;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
pre.next = list1;
list1 = list1.next;
} else {
pre.next = list2;
list2 = list2.next;
}
pre = pre.next;
}
pre.next = list1 == null ? list2 : list1;
return preHead.next;
}
}