-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19_Remove_Nth_Node_From_End_of_List.py
More file actions
55 lines (36 loc) · 1.01 KB
/
Copy path19_Remove_Nth_Node_From_End_of_List.py
File metadata and controls
55 lines (36 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1
Output: []
Example 3:
Input: head = [1,2], n = 1
Output: [1]
Constraints:
The number of nodes in the list is sz.
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
Follow up: Could you do this in one pass?
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(0)
dummy.next = head
firstPtr = dummy
secondPtr = dummy
for _ in range (n+1):
secondPtr = secondPtr.next
while secondPtr:
firstPtr = firstPtr.next
secondPtr = secondPtr.next
firstPtr.next = firstPtr.next.next
return dummy.next