forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeTwoSortedList.java
More file actions
89 lines (87 loc) · 2.19 KB
/
MergeTwoSortedList.java
File metadata and controls
89 lines (87 loc) · 2.19 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
//Without sentry
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode head = null, cur = null;
while(l1 != null || l2 != null){
ListNode next = null;
if(l1 == null){
if(head == null)
head = l2;
else
cur.next = l2;
break;
}
else if(l2 == null){
if(head == null)
head = l1;
else
cur.next = l1;
break;
}
else if(l1.val > l2.val){
next = l2;
l2 = l2.next;
}
else{
next = l1;
l1 = l1.next;
}
if(head == null){
head = next;
cur = head;
}
else{
cur.next = next;
cur = cur.next;
}
}
return head;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
//Use a sentry
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode sen = new ListNode(0);
ListNode head = sen;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
sen.next = l1;
l1 = l1.next;
sen = sen.next;
}
else{
sen.next = l2;
l2 = l2.next;
sen = sen.next;
}
}
sen.next = l1 == null?l2:l1;
return head.next;
}
}