Merge Two Sorted Lists LeetCode solution in Java

1
class Solution {
2
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
3
if (list1 == null && list2 == null) return null;
4
if (list1 == null) return list2;
5
if (list2 == null) return list1;
6

7
ListNode newHead = new ListNode();
8
ListNode newNode = newHead;
9

10
while (list1 != null && list2 != null) {
11
// ListNode newNode = new ListNode();
12
if (list1.val <= list2.val) {
13
newNode.next = list1;
14
list1 = list1.next;
15
} else if (list1.val >= list2.val) {
16
newNode.next = list2;
17
list2 = list2.next;
18
}
19
newNode = newNode.next;
20
}
21
if (list1 != null) newNode.next = list1;
22
else if (list2 != null) newNode.next = list2;
23
return newHead.next;
24
}
25
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0