PS5側板生產商Dbrand上架新側板 並嘲諷索尼無法索賠
阿新 • • 發佈:2021-10-20
給你一個連結串列,刪除連結串列的倒數第n個結點,並且返回連結串列的頭結點。
進階:你能嘗試使用一趟掃描實現嗎?
示例 1:
輸入:head = [1,2,3,4,5], n = 2
輸出:[1,2,3,5]
示例 2:
輸入:head = [1], n = 1
輸出:[]
示例 3:
輸入:head = [1,2], n = 1
輸出:[1]
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
思路
快慢指標
# Definition for singly-linked list.# class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ slow,fast=head,head for i in range(n): fast=fast.next if not fast: #防止[1] 1的情況,此時fast=head=NULL return head.next while fast.next!=None: fast=fast.next slow=slow.next slow.next=slow.next.next return head