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
  • 相关阅读:
    凸松弛技术解密
    机器学习中的逻辑回归模型简介
    机器学习中的损失函数
    逻辑回归的MATLAB实现(二分类问题)
    Lua和C++交互详细总结【转载】
    微擎手机端上传视频(图片)
    IOS开发:UIAlertView使用
    高度自适应问题
    css样式问题
    browser-sync
  • 原文地址:https://www.cnblogs.com/wenqinchao/p/10606727.html
Copyright © 2011-2022 走看看