一次性从单向链表中移除第 k 个元素

Remove kth last element from a Singly Linked List in a single pass

我正在练习 Python,我想不出解决这个问题的方法。 问题是在一次传递和常量 space 中从单向链表中删除第 k 个最后元素。 我只能想到需要 2 遍的解决方案。 另外,在问题中,没有提到列表的大小,所以我假设大小是先验已知的。 谁能告诉我一次完成的方法吗?

在要删除的项目之前将项目的 pointer/location 缓存在临时变量中。

所以会有一个循环,迭代到最后。 会有一条语句在临时缓存中缓存第 (i-k-1) 个元素。

当此循环结束时,temp 将具有要删除的项目的位置。

希望对您有所帮助。

From GeeksforGeeks

Method 2 (Use two pointers)

Maintain two pointers – reference pointer and main pointer. Initialize both reference and main pointers to head. First move reference pointer to n nodes from head. Now move both pointers one by one until reference pointer reaches end. Now main pointer will point to nth node from the end. Return main pointer.

python 中的实现可用。

如果大小已知,那么您要删除 s - kth 元素。

如果不是这种情况,那么我会使用两个跑步者,一个比第二个早 k 个索引。当您的第一个跑步者到达列表末尾时,您的第二个跑步者正好指向第 k 个最后一个元素。