Easy 3-Pointer Approach in Java
Here\'s the algorithm for the code, explained step-by-step:\n\n1. Initialization:\np1: A pointer that traverses the head1 list to reach the node before the inse
Here\'s the algorithm for the code, explained step-by-step:\n\n**1. Initialization:**\np1: A pointer that traverses the head1 list to reach the node before the insertion point (a).\np2: A pointer that traverses the head1 list to reach the node at the insertion point (b).\np3: A pointer that traverses the head2 list.\nres: A pointer that stores the head of the original head1 list (used for returning the final result).\n\n**2. Finding Insertion Nodes:**\nThe first loop iterates a-1 times using p1 to reach the node before the insertion point (a).\nThe second loop iterates b times using p2 to reach the node at the insertion point (b).\n\n**3. Insertion:**\nhead1.next: This line connects the node before the insertion point (p1) to the head of the head2 list (head2). This effectively inserts the head2 list between the two nodes in head1.\np3.next: We iterate through the head2 list using p3 until the last node. The last node\'s next pointer is then assigned the node after the insertion point (p2.next). This connects the head2 list back to the original head1 list after the insertion point.\n\n**4. Returning the Result:**\nThe function returns the res pointer, which still points to the original head of the head1 list. The modified list with the inserted head2 list is now accessible through head1.\n\n\n```\nclass Solution {\n    public ListNode mergeInBetween(ListNode head1, int a, int b, ListNode head2) {\n        \n        ListNode p1 = head1;\n        \n        for(int i=0; i<a-1; i++){\n            p1 = p1.next;\n        }\n        \n        ListNode p2 = head1;\n        \n        for(int i=0; i<b; i++){\n            p2 = p2.next;\n        }\n        \n        ListNode p3 = head2;\n        \n        ListNode res = head1;\n        \n        while(head1!=p1){\n            head1 = head1.next;\n        }\n        \n        head1.next = head2;\n        \n        while(p3.next!=null){\n            p3 = p3.next;\n        }\n        \n        p3.next = p2.next;\n        \n        return res;\n        \n    }\n}\n```
['Linked List', 'Two Pointers', 'Java']