• 131-19. 删除链表的倒数第N个节点


    给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。(第一个我写的时间太长)
    # Definition for singly-linked list.
    class ListNode(object):
        def __init__(self, val=0, next=None):
            self.val = val
            self.next = next
    
    
    class Solution(object):
        def removeNthFromEnd1(self, head, n):
            """
            :type head: ListNode
            :type n: int
            :rtype: ListNode
            """
            if not head.next:
                return
    
            pre = head
            list_data = [head]
            while pre.next:
                list_data.append(pre.next)
                pre = pre.next
            if abs(-n-1) > len(list_data):
                return head.next
            else:
                list_data[-n-1].next = list_data[-n].next
            return head
    
        def removeNthFromEnd2(self, head, n):
            """
            :type head: ListNode
            :type n: int
            :rtype: ListNode
            """
            x = ListNode(100, head)
            m = head
            t = 0
            while m:
                m = m.next
                t += 1
                if t >= n + 1:
                    x = x.next
            if t >= n + 1:
                x.next = x.next.next
            else:
                head = head.next
            return head
    
        def removeNthFromEnd(self, head, n):
            """
            :type head: ListNode
            :type n: int
            :rtype: ListNode
            """
            # if not head.next:
            #     return
    
            root1 = head
            root2 = head
    
            for i in range(n + 1):
                if not root1:
                    return root2.next
                root1 = root1.next
    
            while root1:
                root1 = root1.next
                root2 = root2.next
            root2.next = root2.next.next
            return head
    
    
    if __name__ == '__main__':
        s1 = Solution()
        root = ListNode(1)
        # node1 = ListNode(2)
        # node2 = ListNode(3)
        # node3 = ListNode(4)
        # node4 = ListNode(5)
        #
        # node3.next = node4
        # node2.next = node3
        # node1.next = node2
        # root.next = node1
        print(s1.removeNthFromEnd(root, 1))
    
  • 相关阅读:
    关于UITapGestureRecognizer的一些问题
    自定义导航栏返回按钮
    mousewheel滚轮事件 浏览器的写法
    Apache日志不记录图片文件设置方法和来源日志的配置
    redis持久化配置
    haproxy实现负载均衡
    Keepalived高可用软件的安装与配置
    Sublime text2用户自定义配置
    判断各版本的最简写法
    Ubuntu防火墙 UFW 设置
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/14241843.html
Copyright © 2020-2023  润新知