leetcode Python 19. 刪除連結串列的倒數第N個節點(中等、連結串列)
阿新 • • 發佈:2018-12-04
給定一個連結串列,刪除連結串列的倒數第 n 個節點,並且返回連結串列的頭結點。
示例:
給定一個連結串列: 1->2->3->4->5, 和 n = 2.
當刪除了倒數第二個節點後,連結串列變為 1->2->3->5.
說明:給定的 n 保證是有效的。
思路:給定兩個指標,首先一個先走n步,然後兩個再一起走,直到最早的那個到達終點。其中,有兩種情況,一個是刪除第一個,改變頭結點;一個不是刪除第一個,不用改變頭結點。
# 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 """ pre=head end=head for _ in range(n): end=end.next if not end: return head.next while end.next: pre=pre.next end=end.next pre.next=pre.next.next return head
執行用時: 52 ms, 在Remove Nth Node From End of List的Python3提交中擊敗了86.27% 的使用者