classSolution(object): defremoveNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ fast = slow = head for _ inrange(n): fast = fast.next ifnot fast: return head.next while fast.next: fast = fast.next slow = slow.next slow.next = slow.next.next return head
另一种巧妙的方式
相当于使指针设置在了头结点前,消除了一些边界情况
1 2 3 4 5 6 7 8 9 10 11
defremoveNthFromEnd(self, head, n): slow = fast = self self.next = head while fast.next: if n: n -= 1 else: slow = slow.next fast = fast.next slow.next = slow.next.next return self.next