forked from algorithm016-algorithm016/algorithm016
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution3.java
More file actions
50 lines (45 loc) · 1.35 KB
/
Solution3.java
File metadata and controls
50 lines (45 loc) · 1.35 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
package src.leetcode;
import src.common.node.ListNode;
/**
* 合并两个排序的链表
*/
class Solution3 {
public static void main(String[] args) {
ListNode l1 = ListNode.genNextNode(new int[]{1,3,6,7,8,9,10});
ListNode l2 = ListNode.genNextNode(new int[]{2,3,4});
ListNode listNode = new Solution3().mergeTwoLists2(l1, l2);
System.out.println(listNode);
}
public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
ListNode dum = ListNode.genNextNode(new int[]{0});
ListNode cur = dum;
while (l1 != null && l2 !=null){
if (l1.val <= l2.val) {
cur.next = l1;
l1 =l1.next;
}else{
cur.next =l2;
l2 =l2.next;
}
cur =cur.next;
}
cur.next = l1 !=null ?l1:l2;
return dum.next;
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dum = ListNode.genNextNode(new int[]{0}), cur = dum;
while(l1 != null && l2 != null) {
if(l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
}
else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
cur.next = l1 != null ? l1 : l2;
return dum.next;
}
}