TGViewer
Python | LeetCode Python | LeetCode @easy_python_task · 9.01K subscribers
Post #2447 245
Задача: 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 15, 2026Задача: 1043. Partition Array for Maximum Sum Сложность: medium Если задан целочисленный м…
  2. Oct 15, 2026Post #2446
  3. Oct 14, 2026Задача: 977. Squares of a Sorted Array Сложность: easy Дан целочисленный массив nums, отсо…
  4. Oct 13, 2026Задача: 462. Minimum Moves to Equal Array Elements II Сложность: medium Дан массив целых ч…
  5. Oct 13, 2026Задача: 1056. Confusing Number Сложность: easy Запутанное число - это число, которое при п…
  6. Oct 12, 2026Задача: 104. Maximum Depth of Binary Tree Сложность: easy Дан корень бинарного дерева, вер…
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 →