Skip to content

Commit 70321fa

Browse files
1474_Delete_N_Nodes_After_M_Nodes_of_LinkedList.py
1474_Delete_N_Nodes_After_M_Nodes_of_LinkedList.py solution implemented
1 parent eff82c1 commit 70321fa

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
1474. Delete N Nodes After M Nodes of a Linked List
3+
You are given the head of a linked list and two integers m and n.
4+
5+
Traverse the linked list and remove some nodes in the following way:
6+
7+
Start with the head as the current node.
8+
Keep the first m nodes starting with the current node.
9+
Remove the next n nodes
10+
Keep repeating steps 2 and 3 until you reach the end of the list.
11+
Return the head of the modified list after removing the mentioned nodes.
12+
13+
"""
14+
# Definition for singly-linked list.
15+
# class ListNode:
16+
# def __init__(self, val=0, next=None):
17+
# self.val = val
18+
# self.next = next
19+
class Solution:
20+
def deleteNodes(self, head: ListNode, m: int, n: int) -> ListNode:
21+
prev,curr = head,head
22+
23+
while curr:
24+
slow, fast = m,n
25+
26+
# traverse m nodes
27+
while slow>1 and curr:
28+
prev = curr.next
29+
curr = curr.next
30+
slow -=1
31+
32+
# traverse n nodes
33+
while fast>-1 and curr:
34+
curr = curr.next
35+
fast -=1
36+
37+
# delete n nodes
38+
if prev:
39+
prev.next = curr
40+
prev = curr
41+
42+
return head

0 commit comments

Comments
 (0)