TGViewer
Python | LeetCode Python | LeetCode @easy_python_task · 9.03K subscribers
Post #2166 688
Задача: 1474. Delete N Nodes After M Nodes of a Linked List
Сложность: easy

Вам дано начало связанного списка и два целых числа m и n.

Пройдите по связанному списку и удалите некоторые узлы следующим образом:
Начните с головы как текущего узла.
Сохраните первые m узлов, начиная с текущего узла.
Удалите следующие n узлов.
Продолжайте повторять шаги 2 и 3, пока не достигнете конца списка.
Верните голову изменённого списка после удаления указанных узлов.

Пример:
Input: head = [1,2,3,4,5,6,7,8,9,10,11,12,13], m = 2, n = 3
Output: [1,2,6,7,11,12]
Explanation: Keep the first (m = 2) nodes starting from the head of the linked List (1 ->2) show in black nodes.
Delete the next (n = 3) nodes (3 -> 4 -> 5) show in read nodes.
Continue with the same procedure until reaching the tail of the Linked List.
Head of the linked list after removing nodes is returned.


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

1⃣Инициализация указателей:
Инициализируйте currentNode на голову связанного списка. Этот указатель будет использоваться для линейного прохода по каждому узлу списка.
Инициализируйте lastMNode на голову связанного списка.

2⃣Итерация по списку:
Итеративно удаляйте n узлов после m узлов, продолжая до конца списка.
Проходите m узлов, обновляя lastMNode на текущий узел. После m итераций lastMNode указывает на m-й узел.
Продолжайте итерацию по n узлам.

3⃣Удаление узлов:
Чтобы удалить n узлов, измените указатель next у lastMNode, чтобы он указывал на currentNode после пропуска n узлов.

😎 Решение:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

class Solution:
def deleteNodes(self, head: ListNode, m: int, n: int) -> ListNode:
currentNode = head
lastMNode = head

while currentNode:
mCount, nCount = m, n

while currentNode and mCount > 0:
lastMNode = currentNode
currentNode = currentNode.next
mCount -= 1

while currentNode and nCount > 0:
currentNode = currentNode.next
nCount -= 1

lastMNode.next = currentNode

return head


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_python_task
  1. Oct 12, 2026Задача: 104. Maximum Depth of Binary Tree Сложность: easy Дан корень бинарного дерева, вер…
  2. Oct 11, 2026Post #2439
  3. Oct 11, 2026Задача: 997. Find the Town Judge Сложность: easy В городе есть n человек, помеченных от 1…
  4. Oct 11, 2026Post #2437
  5. Oct 11, 2026Задача: 436. Find Right Interval Сложность: medium Дан массив интервалов, где intervals[i]…
  6. Oct 10, 2026Задача: 1249. Minimum Remove to Make Valid Parentheses Сложность: medium Дана строка s из…
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 →