zoukankan      html  css  js  c++  java
  • 删除链表中的倒数第n个元素

    示例:

    输入链表:1->2->3->4->5 , 2

    输出:1->2->3->5

    Python解决方案1:

    # 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
            """
            list_ = [head.val]
            while head.next:
                list_.append(head.next.val)
                head.next = head.next.next
                
            list_.pop(-n)
            if not list_:
                return None
            out_head = ListNode(list_[0])
            first = out_head
            for i in list_[1:]:
                a = ListNode(i)
                first.next = a
                first = first.next
            return out_head

    Python解决方案2:

    # 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
            """
    
            length = 0
            first = ListNode(0)
            first.next = head
            while first.next:
                first.next = first.next.next
                length += 1
                
                
            prev = ListNode(0)
            if length == n:
                prev.next = head.next
            else:
                prev.next = head     
                
            i = 0
            while head.next:
                if i != length - n -1:
                    head = head.next
                else:
                    if head.next.next:
                        head.next = head.next.next
                        head = head.next
                    else:
                        head.next = None
                i += 1
            return prev.next
  • 相关阅读:
    orm 锁 和 事务
    多表查询
    django 单表查询
    djgango装饰器
    几个SQL命令的使用
    怎么成为优秀的软件模型设计者?
    jbpm 工作流(二)
    Jbpm工作流(一)
    EJB 介绍
    JNDI 使用
  • 原文地址:https://www.cnblogs.com/wenqinchao/p/10606727.html
Copyright © 2011-2022 走看看