zoukankan      html  css  js  c++  java
  • LeetCode:19. 删除链表的倒数第N个节点

    1、题目描述

    给定一个链表,删除链表的倒数第 个节点,并且返回链表的头结点。

    示例:

      给定一个链表: 1->2->3->4->5, 和 n = 2.

      当删除了倒数第二个节点后,链表变为 1->2->3->5.

    说明:

    给定的 n 保证是有效的。

    进阶:

    你能尝试使用一趟扫描实现吗?

    2、题解

    2.1、解法一

    class ListNode:
        def __init__(self, x):
            self.val = x
            self.next = None
    
    class Solution:
    
        def __init__(self):
            self.h = None
            self.num = 0
    
        def add(self, val):
            if self.h == None:
                self.h = ListNode(val)
                self.num += 1
                return
    
            node = self.h
            while node.next:
                node = node.next
    
            node.next = ListNode(val)
            self.num += 1
        
        def get_length(self,head):
            node = head
            if head == None:
                return 0
            count = 0
            while node:
                count += 1
                node = node.next
            return count
    
        def remove(self,head,n):
            node = head
            prev = node
            count = 0
            ret_list = []
            while node:
                print(":",node.val)
                if count == n:
                    prev.next = node.next
                    self.num -= 1
                else:
                    ret_list.append(node.val)
                    prev = node
                node = node.next
                count += 1
    
            return ret_list
    
        def removeNthFromEnd(self, head, n):
            """
            :type head: ListNode
            :type n: int
            :rtype: ListNode
            """
            print(self.get_length(head))
            ret = self.remove(head,self.get_length(head) -n)
            return ret
    

      

  • 相关阅读:
    js --- for in 和 for of
    vue -- config index.js 配置文件详解
    vue -- 脚手架之webpack.dev.conf.js
    vue --- 解读vue的中webpack.base.config.js
    vue 引入第三方字体包
    js call 和 apply
    vue2.0中的$router 和 $route的区别
    懒加载js实现和优化
    vue的指令在webstrom下报错
    BFC的布局规则和触发条件
  • 原文地址:https://www.cnblogs.com/bad-robot/p/10064968.html
Copyright © 2011-2022 走看看