mycode 88.29%
关键是一定要head前新建一个节点,否则要分类讨论很多次来避免slow或者fast出现None.next的错误
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ dummy = ListNode(-1) dummy.next = head slow = fast = dummy #print(n,head.val) while n: fast = fast.next n -= 1 #print(n,head.val,fast) while fast and fast.next: fast = fast.next slow = slow.next slow.next = slow.next.next return dummy.next
例如,下面这种情况就要分情况讨论,但是会更快
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head, n): fast = slow = head for _ in range(n): fast = fast.next if not fast: #例如1-》2-》3-》4-》None,n=4或者5的时候,删除的就应该是第一个节点,所以返回head.next就好
return head.next while fast.next: fast = fast.next slow = slow.next slow.next = slow.next.next return head