DEV Community

Tanuja V
Tanuja V

Posted on • Edited on

Merge In Between Linked Lists | LeetCode | Java

Algorithm

  1. Initialization:
    p1 : A pointer that traverses the head1 list to reach the node before the insertion point (a).
    p2 : A pointer that traverses the head1 list to reach the node at the insertion point (b).
    p3 : A pointer that traverses the head2 list.
    res : A pointer that stores the head of the original head1 list (used for returning the final result).

  2. Finding Insertion Nodes:
    The first loop iterates a-1 times using p1 to reach the node before the insertion point (a).
    The second loop iterates b times using p2 to reach the node at the insertion point (b).

  3. Insertion:
    head1.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.
    p3.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.

  4. Returning the Result:
    The 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.

Code

class Solution {
    public ListNode mergeInBetween(ListNode head1, int a, int b, ListNode head2) {

        ListNode p1 = head1;

        for(int i=0; i<a-1; i++){
            p1 = p1.next;
        }

        ListNode p2 = head1;

        for(int i=0; i<b; i++){
            p2 = p2.next;
        }

        ListNode p3 = head2;

        ListNode res = head1;

        while(head1!=p1){
            head1 = head1.next;
        }

        head1.next = head2;

        while(p3.next!=null){
            p3 = p3.next;
        }

        p3.next = p2.next;

        return res;

    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Top comments (0)