diff --git a/src/main/java/com/fishercoder/solutions/_1669.java b/src/main/java/com/fishercoder/solutions/_1669.java index befb3283d8..673e1655fb 100644 --- a/src/main/java/com/fishercoder/solutions/_1669.java +++ b/src/main/java/com/fishercoder/solutions/_1669.java @@ -5,6 +5,7 @@ public class _1669 { public static class Solution1 { public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) { + ListNode pre = new ListNode(-1); ListNode list1Temp = list1; pre.next = list1Temp; @@ -33,4 +34,24 @@ public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) { return pre.next; } } + public static class Solution2 { + public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) { + ListNode endList = list1; + ListNode startList = null; + + for (int i = 0; i < b; i++, endList = endList.next) { + if (i == a - 1) { + startList = endList; + } + } + // Connect the startList.next to list2 + startList.next = list2; + while (list2.next != null) { + list2 = list2.next; + } + list2.next = endList.next; + endList.next = null; + return list1; + } + } } diff --git a/src/test/java/com/fishercoder/_1669Test.java b/src/test/java/com/fishercoder/_1669Test.java index 395403d86f..aaecb5a2b8 100644 --- a/src/test/java/com/fishercoder/_1669Test.java +++ b/src/test/java/com/fishercoder/_1669Test.java @@ -2,16 +2,18 @@ import com.fishercoder.common.classes.ListNode; import com.fishercoder.common.utils.LinkedListUtils; -import com.fishercoder.solutions._1; -import com.fishercoder.solutions._1669; import org.junit.BeforeClass; +import org.junit.Test;import org.junit.BeforeClass; import org.junit.Test; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import com.fishercoder.solutions._1669; public class _1669Test { private static _1669.Solution1 solution1; + private static _1669.Solution1 solution2; + private static ListNode l1; + private static ListNode l2; + private static int a; + private static int b; private static ListNode list1; private static ListNode list2; private static ListNode expected; @@ -20,6 +22,7 @@ public class _1669Test { @BeforeClass public static void setup() { solution1 = new _1669.Solution1(); + solution2 = new _1669.Solution2(); } @Test @@ -31,5 +34,12 @@ public void test1() { LinkedListUtils.printList(actual); assertEquals(expected, actual); } - -} \ No newline at end of file + @Test + public void test2() { + l1 = ListNode.createSinglyLinkedList(Arrays.asList(0, 1, 2, 3, 4, 5)); + l2 = ListNode.createSinglyLinkedList(Arrays.asList(1000000,1000001,1000002)); + a = 3; + b = 4; + assertEquals(ListNode.createSinglyLinkedList(Arrays.asList(0,1,2,1000000,1000001,1000002,5)), solution2.mergeInBetween(l1, a, b, l2)); + } +}