Skip to content

Commit b2188e0

Browse files
authored
Update Merge Two Sorted Lists.java
1 parent 9bc4661 commit b2188e0

File tree

1 file changed

+27
-15
lines changed

1 file changed

+27
-15
lines changed

Easy/Merge Two Sorted Lists.java

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,26 +10,38 @@
1010
*/
1111
class Solution {
1212
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
13-
ListNode dummy = new ListNode(-1);
14-
ListNode curr = dummy;
15-
while (list1 != null || list2 != null) {
16-
if (list1 != null && list2 != null) {
17-
if (list1.val > list2.val) {
18-
curr.next = new ListNode(list2.val);
19-
list2 = list2.next;
20-
} else {
21-
curr.next = new ListNode(list1.val);
22-
list1 = list1.next;
13+
if (list1 == null || list2 == null) {
14+
return list1 == null ? list2 : list1;
15+
}
16+
ListNode prev = null;
17+
ListNode head = null;
18+
while (list1 != null && list2 != null) {
19+
if (list1.val <= list2.val) {
20+
prev = list1;
21+
if (head == null) {
22+
head = list1;
2323
}
24-
} else if (list1 != null && list2 == null) {
25-
curr.next = new ListNode(list1.val);
2624
list1 = list1.next;
2725
} else {
28-
curr.next = new ListNode(list2.val);
26+
ListNode node = list2;
2927
list2 = list2.next;
28+
if (prev == null) {
29+
node.next = list1;
30+
prev = node;
31+
head = prev;
32+
} else {
33+
prev.next = node;
34+
node.next = list1;
35+
prev = node;
36+
}
3037
}
31-
curr = curr.next;
3238
}
33-
return dummy.next;
39+
if (list2 != null) {
40+
prev.next = list2;
41+
}
42+
if (list1 != null) {
43+
prev.next = list1;
44+
}
45+
return head;
3446
}
3547
}

0 commit comments

Comments
 (0)