1669. Merge In Between Linked Lists - Medium

前往題目

想法

  • 簡單的拆開後連接

思路

  1. 找到第一個斷點,以及第二個斷點
  2. 把兩個斷點接上list2的頭和尾

Code

class Solution {
    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
        ListNode breakPointFront = list1, breakPointRear = list1;
        // Find the first break point
        for (int i = 0; i < a - 1; ++i) {
            breakPointFront = breakPointFront.next;
        }

        breakPointRear = breakPointFront;

        // Cal. the steps to the rear break point
        b = b - a + 2;

        // Find the second break point
        for (int i = 0; i < b; ++i) {
            breakPointRear = breakPointRear.next;
        }

        // Connect
        breakPointFront.next = list2;

        // Until the rear node of the list2
        while (list2.next != null) {
            list2 = list2.next;
        }
        
        // Connect the rear part
        list2.next = breakPointRear;
        return list1;
    }
}

1669. Merge In Between Linked Lists - Medium
https://f88083.github.io/2024/10/03/1669-Merge-In-Between-Linked-Lists-Medium/
作者
Simon Lai
發布於
2024年10月3日
許可協議