TGViewer
Swift | LeetCode Swift | LeetCode @easy_swift_task · 1.3K subscribers
Post #1043 107
Задача: 1669. Merge In Between Linked Lists
Сложность: medium

Вам даны два связанных списка: list1 и list2 размером n и m соответственно.

Удалите узлы list1 с ath узла по bth узел и вставьте на их место list2.

Синие ребра и узлы на рисунке в вверху поста указывают на результат:

Пример:
Input: list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
Output: [10,1,13,1000000,1000001,1000002,5]
Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.


👨‍💻 Алгоритм:

1⃣Инициализация и добавление узлов из list1 до узла a в массив:
Инициализировать переменную index равную 0 и current1 равную list1.
Пока index меньше a, добавлять current1.val в массив mergeArray, перемещаться к следующему узлу current1.next и увеличивать index.

2⃣Добавление узлов из list2 в массив:
Инициализировать current2 равную list2.
Пока current2 не равен null, добавлять current2.val в mergeArray и перемещаться к следующему узлу current2.next.

3⃣Добавление узлов из list1 от узла b + 1 до конца в массив и создание нового связанного списка:
Найти узел на позиции b + 1, перемещая current1 и увеличивая index, пока index меньше b + 1.
Добавлять узлы из current1 в массив, пока current1 не станет null.
Создать новый связанный список из значений в mergeArray, добавляя узлы в начало списка и возвращая его.

😎 Решение:
class Solution {
func mergeInBetween(_ list1: ListNode?, _ a: Int, _ b: Int, _ list2: ListNode?) -> ListNode? {
var mergeArray = [Int]()
var index = 0
var current1 = list1

while index < a {
mergeArray.append(current1!.val)
current1 = current1!.next
index += 1
}

var current2 = list2
while current2 != nil {
mergeArray.append(current2!.val)
current2 = current2!.next
}

while index < b + 1 {
current1 = current1!.next
index += 1
}

while current1 != nil {
mergeArray.append(current1!.val)
current1 = current1!.next
}

var resultList: ListNode? = nil
for val in mergeArray.reversed() {
let newNode = ListNode(val, resultList)
resultList = newNode
}

return resultList
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_swift_task
  1. Oct 13, 2026Задача: 786. K-th Smallest Prime Fraction Сложность: medium Вам дан отсортированный массив…
  2. Oct 11, 2026Задача: 1325. Delete Leaves With a Given Value Сложность: medium Дано корневое дерево root…
  3. Oct 7, 2026🔥 Скрытые вакансии с удаленной работой для iOS разработчика, которые нигде больше не публ…
  4. Oct 4, 2026Задача: 523. Continuous Subarray Sum Сложность: medium Дан целочисленный массив nums и цел…
  5. Oct 4, 2026Задача: 1329. Sort the Matrix Diagonally Сложность: medium Диагональ матрицы — это диагона…
  6. Oct 3, 2026Задача: 200. Number of Islands Сложность: medium Дана двумерная бинарная сетка размером m…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →