LeetCode Everyday:堅持價值投資,做時間的朋友!!!
題目:
給定一個鏈表,刪除鏈表的倒數第n
個節點,並且返回鏈表的頭結點。
進階:你能嘗試使用一趟掃描實現嗎?
示例:
- 示例 1:
給定一個鏈表: 1->2->3->4->5, 和 n = 2. 當刪除了倒數第二個節點後,鏈表變爲 1->2->3->5.
代碼
方法一: 遞歸 題解
執行用時:32 ms, 在所有 Python3 提交中擊敗了98.09%的用戶
內存消耗:13.5 MB, 在所有 Python3 提交中擊敗了5.41%的用戶
# 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
"""
global i
if head is None:
i=0
return None
head.next = self.removeNthFromEnd(head.next,n)
i+=1
return head.next if i==n else head
"""
For Example: input: 1->2->3->4->5, 和 n = 2
output: 1->2->3->5
"""
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
n = 2
solution = Solution()
result = solution.removeNthFromEnd(head, n)
print('輸出爲:%d->%d->%d->%d' % (result.val, result.next.val, result.next.next.val, result.next.next.next.val))
方法二: 快慢指針 題解
執行用時:48 ms, 在所有 Python3 提交中擊敗了35.30%的用戶
內存消耗:13.7 MB, 在所有 Python3 提交中擊敗了5.41%的用戶
# 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
"""
dummy = ListNode(0)
dummy.next = head
fast,slow = dummy,dummy
for i in range(n+1):
fast = fast.next
while fast is not None:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
"""
For Example: input: 1->2->3->4->5, 和 n = 2
output: 1->2->3->5
"""
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
n = 2
solution = Solution()
result = solution.removeNthFromEnd(head, n)
print('輸出爲:%d->%d->%d->%d' % (result.val, result.next.val, result.next.next.val, result.next.next.next.val))
參考
- https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/python-di-gui-by-adamch0u/
- https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/guan-fang-ti-jie-de-python3-shi-xian-fu-ya-jie-dia/