-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMergeTwoSortedLists.java
More file actions
40 lines (31 loc) · 1.17 KB
/
MergeTwoSortedLists.java
File metadata and controls
40 lines (31 loc) · 1.17 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
// Merge two sorted linked lists and return it as a new list.
// The new list should be made by splicing together the nodes of the first two lists.
// See: https://leetcode.com/problems/merge-two-sorted-lists/
// TODO: The problem can be done with O(1) space complexity
package leetcode.linkedlist;
import static leetcode.util.linkedlist.LinkedListUtil.*;
import leetcode.util.linkedlist.ListNode;
public class MergeTwoSortedLists {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode result = head;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
head.next = l1;
l1 = l1.next;
} else {
head.next = l2;
l2 = l2.next;
}
head = head.next;
}
head.next = l1 != null ? l1 : l2; // tail nodes
return result.next;
}
public static void main(String[] args) {
MergeTwoSortedLists sln = new MergeTwoSortedLists();
ListNode l1 = initList(1, 2, 4);
ListNode l2 = initList(1, 3, 4);
printLinkedList(sln.mergeTwoLists(l1, l2));
}
}