Best/Easiest Java Code 🔥
Intuition\nWe need to replace nodes from the ath node to the bth node of list1 with the entire list2. To do this, we find the node before ath and the node after
# Intuition\nWe need to replace nodes from the ath node to the bth node of list1 with the entire list2. To do this, we find the node before ath and the node after bth in list1. Then, we connect the node before ath to the head of list2 and the tail of list2 to the node after bth.\n\n# Approach\n1. Traverse list1 until the node before ath node and store it.\n2. Traverse list1 from ath node to (b+1)th node and store the node after bth node.\n3. Find the tail of list2.\n4. Connect the node before ath to the head of list2.\n5. Connect the tail of list2 to the node after bth.\n6. Return the modified list1.\n\n# Complexity\n- Time complexity:\nO(a + b + list2.length)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {\n        // Initialize current node to traverse list1\n        ListNode currNode = list1;\n        // Initialize index to keep track of current position in list1\n        int index = 0;\n        \n        // Traverse list1 until the node before ath node\n        while (index < a - 1) {\n            currNode = currNode.next;\n            index++;\n        }\n        // Store the node before ath node\n        ListNode front = currNode;\n        \n        // Traverse list1 from ath node to (b+1)th node\n        while (index < b + 1) {\n            currNode = currNode.next;\n            index++;\n        }\n        // Store the node after bth node\n        ListNode rear = currNode;\n        \n        // Find the tail of list2\n        ListNode secondListTail = list2, secondListHead = list2;\n        while (secondListTail.next != null) {\n            secondListTail = secondListTail.next;\n        }\n        \n        // Connect the front node to the head of list2\n        front.next = secondListHead;\n        // Connect the tail of list2 to the rear node\n        secondListTail.next = rear;\n        \n        // Return the modified list1\n        return list1;\n    }\n}\n\n```
['Java']