Skip to content

Commit 69af013

Browse files
add iterative solution for 21
1 parent 9b1b3ef commit 69af013

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/main/java/com/fishercoder/solutions/_21.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,30 @@ public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
3838
}
3939
}
4040

41+
public static class Solution2 {
42+
/**
43+
* iterative solution
44+
* Time: O(m+n)
45+
* Space: O(1)
46+
*/
47+
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
48+
ListNode pre = new ListNode(-1);
49+
ListNode curr = pre;
50+
51+
while (l1 != null && l2 != null) {
52+
if (l1.val < l2.val) {
53+
curr.next = l1;
54+
l1 = l1.next;
55+
} else {
56+
curr.next = l2;
57+
l2 = l2.next;
58+
}
59+
curr = curr.next;
60+
}
61+
62+
curr.next = l1 == null ? l2 : l1;
63+
return pre.next;
64+
}
65+
}
66+
4167
}

src/test/java/com/fishercoder/_21Test.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,14 @@
1111

1212
public class _21Test {
1313
private static _21.Solution1 solution1;
14+
private static _21.Solution2 solution2;
1415
private static ListNode l1;
1516
private static ListNode l2;
1617

1718
@BeforeClass
1819
public static void setup() {
1920
solution1 = new _21.Solution1();
21+
solution2 = new _21.Solution2();
2022
}
2123

2224
@Test
@@ -26,4 +28,11 @@ public void test1() {
2628
assertEquals(ListNode.createSinglyLinkedList(Arrays.asList(1, 2, 3, 4, 5)), solution1.mergeTwoLists(l1, l2));
2729
}
2830

31+
@Test
32+
public void test2() {
33+
l1 = ListNode.createSinglyLinkedList(Arrays.asList(1, 3, 5));
34+
l2 = ListNode.createSinglyLinkedList(Arrays.asList(2, 4));
35+
assertEquals(ListNode.createSinglyLinkedList(Arrays.asList(1, 2, 3, 4, 5)), solution2.mergeTwoLists(l1, l2));
36+
}
37+
2938
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy