JAVA solution: Easy Explanation
Intuition\n Describe your first thoughts on how to solve this problem. \nThe naive approach of the solution is that, we declare a new linked list and copy the l
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe naive approach of the solution is that, we declare a new linked list and copy the `list1` in new list upto `a` and the further traverse `list2` and copy them in the new linked list and again traverse `list1` upto `b` and start copying and then finally return the head of the new linked list.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe step by step approach to solve this problem is described below:\n1. First traverse list1 upto `a-1` and store its address at `curr1` and again traverse the same `list1` upto position b and store its address at `curr2`.\n2. Set the `curr1 next` address as the starting address of `list2`.\n3. Further traverse `list2` upto the last node and finally set the next of last node of `list2` as `curr2 next.`\n4. Return `list1.`\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ where n is the length of the `list1`\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n***KINDLY UPVOTE THIS SOLUTION.***\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        int i=1;\n        ListNode curr1=list1, curr2=list1;\n    // Traversing list1 to store address of a-1 in curr1\n        while(i<a){\n            curr1=curr1.next;\n            i++;\n        }\n        i=0;\n    //Traversing list2 to store address of b in curr2\n        while(i<b){\n            curr2=curr2.next;\n            i++;\n        }\n    //curr1\'s next store the starting address of list2\n        curr1.next=list2;\n    // Traversing list2 to reach the last node\n        while(list2.next!=null)\n            list2=list2.next;\n    // The last node of list2 next value should store the address of curr2.next\n        list2.next=curr2.next;\n        return list1;\n    }\n}\nKINDLY UPVOTE THIS SOLUTION IF YOU FIND IT USEFUL.
['Java']