-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem19.py
More file actions
32 lines (27 loc) · 814 Bytes
/
Problem19.py
File metadata and controls
32 lines (27 loc) · 814 Bytes
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
class Optional:
pass
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
pass
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
# checking if the head exists or if its a single node
if not head or (head.next == None and n == 1):
return []
dummy = ListNode(0)
dummy.next = head
length = 0
first = head
while first is not None:
length += 1
first = first.next
length -= n
first = dummy
while length > 0:
length -= 1
first = first.next
first.next = first.next.next
# returning the node next to the head
return dummy.next