Home [Medium] Merge In Between Linked Lists
Post
Cancel

[Medium] Merge In Between Linked Lists

‘Merge In Between Linked Lists (Medium)`


📌 Problem

https://leetcode.com/problems/merge-in-between-linked-lists/

📌 Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
        ListNode left = list1;
        for (int i = 1; i < a; i++)
            left = left.next;

        ListNode middle = left;
        for (int i = a; i <= b; i++)
            middle = middle.next;
        
		left.next = list2;
        while (list2.next != null)
            list2 = list2.next;
        
        list2.next = middle.next;
        
        return list1;
    }
}
This post is licensed under CC BY 4.0 by the author.

[Medium] Maximum Twin Sum of a Linked List

[Medium] Merge Nodes in Between Zeros

Comments powered by Disqus.