刪除連結串列倒數第N個節點
阿新 • • 發佈:2021-06-29
# 給你一個連結串列,刪除連結串列的倒數第 n 個結點,並且返回連結串列的頭結點。
#
# 進階:你能嘗試使用一趟掃描實現嗎?
#
#
#
# 示例 1:
#
#
# 輸入:head = [1,2,3,4,5], n = 2
# 輸出:[1,2,3,5]
方法:雙指標
# leetcode submit region begin(Prohibit modification and deletion) # 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: ListNode, n: int) -> ListNode: dummy = ListNode(0, head) # 啞節點指向頭結點 first = head # 快指標指向頭結點 second = dummy # 慢指標指向啞節點 # 快指標先走n fori in range(n): first = first.next # 直至快指標為空,到連結串列結尾 while first: first = first.next second = second.next # 慢指標的next指向刪除節點的next節點 second.next = second.next.next # 返回頭結點 return dummy.next # leetcode submit region end(Prohibit modification and deletion)