• leetcode-easy-listnode-19 remove nth node from end of list


    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
  • 相关阅读:
    Linux内核TSS的使用
    DPL, CPL及RPL之间的关系
    Linux内存管理(深入理解Linux内核)
    Windows下安装PIL进行图像处理
    内存Zone中的pageset成员分析
    导出符号的意义
    GDI及Windows的消息机制
    kmalloc vs vmalloc
    Linux Kernel Development有关内存管理
    STL sort
  • 原文地址:https://www.cnblogs.com/rosyYY/p/10997194.html
Copyright © 2020-2023  润新知