-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path03_MergeSortedLists.java
More file actions
53 lines (44 loc) · 1.28 KB
/
03_MergeSortedLists.java
File metadata and controls
53 lines (44 loc) · 1.28 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
// Problem: Merge Two Sorted Linked Lists
// Author: Ataul (codeByunique)
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
class MergeSortedLists {
public static void main(String[] args) {
// List 1: 1 -> 3 -> 5
ListNode l1 = new ListNode(1);
l1.next = new ListNode(3);
l1.next.next = new ListNode(5);
// List 2: 2 -> 4 -> 6
ListNode l2 = new ListNode(2);
l2.next = new ListNode(4);
l2.next.next = new ListNode(6);
ListNode merged = mergeTwoLists(l1, l2);
System.out.print("Merged List: ");
while (merged != null) {
System.out.print(merged.val + " ");
merged = merged.next;
}
}
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
ListNode tail = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
tail.next = l1;
l1 = l1.next;
} else {
tail.next = l2;
l2 = l2.next;
}
tail = tail.next;
}
// Attach the remaining part
tail.next = (l1 != null) ? l1 : l2;
return dummy.next;
}
}