-
Notifications
You must be signed in to change notification settings - Fork 0
/
19.py
42 lines (41 loc) · 1.36 KB
/
19.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
# 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]:
"""
TODO
兩種解題思路:
1. 取得總長度, 用正數的方式移除
2. 快慢指針, 先將快指針走n步, 接著一起走, 當快指針走到底時, 慢指針會停在要移除節點的前一點
"""
# values = list()
# while head:
# values.append(head.val)
# head = head.next
#
# ans = None
# for index, value in enumerate(reversed(values)):
# if index == n - 1:
# continue
# if not ans:
# ans = ListNode(val=value, next=None)
# else:
# ans = ListNode(val=value, next=ans)
# return ans
fast = ListNode(val=0, next=head)
slow = ListNode(val=0, next=head)
move = 0
while fast.next.next:
move += 1
fast.next = fast.next.next
if move > n:
slow.next = slow.next.next
if n - move == 1:
# 移除頭一個節點
return head.next
else:
slow.next.next = slow.next.next.next
return head