-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode_19.py
More file actions
43 lines (41 loc) · 1.12 KB
/
LeetCode_19.py
File metadata and controls
43 lines (41 loc) · 1.12 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
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# fast ,slow =head, head
# if n == 1 and not head.next:
# # print(n)
# return []
# while n:
# if fast is None:
# return None
# fast = fast.next
# n = n-1
# while fast.next:
# slow = slow.next
# fast = fast.next
# if not slow.next:
# return None
# slow.next = slow.next.next
# return head
if n == 1 and not head.next:
return None
fast, slow = head, head
while n and fast:
fast = fast.next
n -= 1
if not fast:
return head.next
while fast.next:
slow = slow.next
fast = fast.next
temp = slow.next.next
del slow.next
slow.next = temp
if __name__ == "__main__":
head = ListNode(1)
head.next=ListNode(2)
Solution().removeNthFromEnd(head, 1)
print(head.val)