Merge Portion of One Linked List with Another
Intuition\n Describe your first thoughts on how to solve this problem. \nWhen approaching this problem, we want to find the portion of the first list that needs
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen approaching this problem, we want to find the portion of the first list that needs to be replaced with the second list. We\'ll locate the starting and ending points of this portion in the first list and then stitch the second list in between.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStart by traversing the first list until we find the node at the starting index a.\n\nContinue traversing until we reach the node at the ending index b, while keeping track of the node immediately after this portion to be replaced.\n\nTraverse through the second list to find its last node, which will be the tail.\n\nConnect the beginning of the second list to the node just before the portion to be replaced in the first list.\n\nConnect the end of the second list (its tail) to the node just after the portion to be replaced in the first list.\n\nFinally, return the modified first list.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime complexity: We traverse both lists once, so the time complexity is O(n), where n is the total number of nodes in both lists.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace complexity: We use a few extra pointers, but we don\'t use additional data structures that scale with the input size, so the space complexity is O(1)\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n *     int val;\n *     ListNode next;\n *     ListNode() {}\n *     ListNode(int val) { this.val = val; }\n *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {\n        \n        int idx = 1;\n        ListNode temp1L1 = list1;\n        while(idx < a){\n            temp1L1 = temp1L1.next;\n            idx++;\n        }\n        ListNode temp2L1 = temp1L1;\n        while(idx <= b+1){\n            temp2L1 = temp2L1.next;\n            idx++;\n        }\n\n        ListNode tailL2 = list2;\n        ListNode headL2 = list2;\n        while(tailL2.next!=null){\n            tailL2 = tailL2.next;\n        }\n        temp1L1.next = headL2;\n        tailL2.next = temp2L1;\n        return list1;\n\n    }\n}\n```
['Java']