給定一個長度大于等于n的鏈表,刪除其倒數第n個元素
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'thinkreed'
__mtime__ = '2017/3/21'
"""
# 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
thanks to https://discuss.leetcode.com/topic/14692/3-short-python-solutions
"""
#一個快,一個慢
fast = slow = head
#先讓快的比慢的先走n個
for _ in range(n):
fast = fast.next
#整個鏈表長度等于n,所以倒數第n個就是頭部
if not fast:
return head.next
#當循環結束時,慢指針slow恰好走到倒數第n個
while fast.next:
fast = fast.next
slow = slow.next
#刪除倒數第n個
slow.next = slow.next.next
return head