zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):链表类:第19题:删除链表的倒数第N个节点:给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。说明: 给定的 n 保证是有效的。

    题目:
    删除链表的倒数第N个节点:给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。说明:  给定的 n 保证是有效的。
    思路:
    这道题以前见过,好像是一个叫睿企还是睿智的科技公司的笔试题。使用两个指针,这两个指针的间隔是n。
    程序:
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    class Solution:
        def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
            if not head:
                return None
            if n == 0:
                return head
            fast = head
            for index in range(n):
                fast = fast.next
            slow = head
            if not fast:
                return head.next
            while fast.next:
                slow = slow.next
                fast = fast.next
            slow.next = slow.next.next
            return head
  • 相关阅读:
    CentOS 7 修改国内yum源
    k8s 安装
    python2 python3同时安装了scrapy如何区分调用
    scrapy log 设置
    hello django
    linux 分割大文件
    scrapy 对不同的Item进行分开存储
    纯C实现的一套low b 贪吃蛇(娱乐版)
    Python之如何实现一行输入多个值
    HDU2571:命运(DP)
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12811719.html
Copyright © 2011-2022 走看看