以下截图来自于 VSCode 的 LeetCode 插件:
需要注意几点
- python不同于C语言,是一种按对象引用传递的语言,详细介绍见:
- https://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/
- 只需扫描一遍,用ptr[]记录每个结点的引用,用内存换取时间
#
# @lc app=leetcode.cn id=19 lang=python
#
# [19] 删除链表的倒数第 N 个结点
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
# python是按对象传递引用的语言
ptr = []
p = head
count = 0
# 遍历一次,保存每个结点的引用对象
while p:
ptr.append(p)
p = p.next
count += 1
# 特殊情况,去掉首结点
if n == count:
return head.next
ptr[count-n-1].next = ptr[count-n].next
return head
# @lc code=end
代码性能



