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
原文地址:https://www.cnblogs.com/zhuozige/p/12811719.html