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
  • 相关阅读:
    设计模式 创建型 单例模式
    设计模式 创建型 抽象工厂模式
    设计模式六大原则
    设计模式 创建型 工厂方法模式
    设计模式 创建型 简单工厂模式
    Junit TDD
    覆盖索引
    多列索引 单列索引
    JDBC PreparedStatement Statement
    常用·SQL
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12811719.html
Copyright © 2011-2022 走看看