-
Notifications
You must be signed in to change notification settings - Fork 19
/
answer.py
43 lines (35 loc) · 1.11 KB
/
answer.py
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
#!/usr/bin/python
#------------------------------------------------------------------------------
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if head:
fast = head
slow = head
for _ in range(n):
if fast:
fast = fast.next
else:
return None
# head case
if not fast:
head = head.next
return head
# This will bring slow up to the correct node
while fast.next:
fast = fast.next
slow = slow.next
# Remove the node after slow
slow.next = slow.next.next
return head
#------------------------------------------------------------------------------
#Testing