美文网首页
算法---删除链表倒数第n个元素

算法---删除链表倒数第n个元素

作者: reedthinking | 来源:发表于2017-07-14 23:33 被阅读0次

    给定一个长度大于等于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
    

    相关文章

      网友评论

          本文标题:算法---删除链表倒数第n个元素

          本文链接:https://www.haomeiwen.com/subject/szxahxtx.html