简体   繁体   English

如何删除O(1)中单链接列表的最后一个元素?

[英]How to remove last element for a Singly Linked list in O(1)?

Assume that I have a singly linked list with sentinel. 假设我有一个与哨兵的单链表。 To remove the last element in O(1) time, I need to maintain handle to last 2 elements. 要删除O(1)时间中的最后一个元素,我需要维护最后2个元素的句柄。 But maintaining handle to last two elements complicates the add operation. 但是保持最后两个元素的句柄会使添加操作复杂化。

Is there a way to remove the last element of a singly linked list with sentinel in O(1) without maintaining handle to last 2 elements? 有没有办法删除O(1)中带有哨兵的单链接列表的最后一个元素,而又不维护最后2个元素的句柄? I would much appreciate any sample code in java. 我将非常感谢Java中的任何示例代码。

Thanks. 谢谢。

With a singly linked list implemented in the normal way will be an O(N) operation. 使用以常规方式实现的单链接列表将执行O(N)操作。

Retaining a handle on the last element isn't that complicated, and singly-linked list implementations often do it so that you can add at the end in O(1) . 保留最后一个元素的句柄并不那么复杂,单链接列表实现通常会这样做,以便可以在O(1)的末尾添加。 However, maintaining the link to the last element in the face of an O(1) "remove last" operation is not possible. 但是,不可能在O(1) “删除最后一个”操作中维持到最后一个元素的链接。

Think about it. 想一想。 Suppose I have somewhere to keep pointers to the last and 2nd to last nodes. 假设我在某处保留指向最后一个节点和第二个到最后一个节点的指针。 When I remove the last node, I need to: 当我删除最后一个节点时,我需要:

  1. Update the next pointer in the 2nd to last node to be null, 将第二个到最后一个节点中的next指针更新为null,
  2. Update the last pointer to point to the 2nd to last node. 更新last指针以指向倒数第二个节点。
  3. Update the secondToLast pointer to point to the node before it. 更新secondToLast指针以指向它之前的节点。

But how do I do the last step without traversing the list from the start ... which is an O(N) operation? 但是,如何在不从头开始遍历列表的情况下执行最后一步...这是O(N)操作?

Now I suppose you could code your linked list so that removing the last element is O(1) the first time you do it , and O(N) on subsequent times ... until you add a new element at the end. 现在,我想您可以对链表进行编码,以使删除的最后一个元素是第一次执行 O(1) ,而在以后的操作中删除O(N) ...直到最后添加一个新元素。 But unless you've got an unusual use-case, this "optimization" won't be worth it. 但是除非您有一个不寻常的用例,否则这种“优化”是不值得的。


You are probably better off using java.util.LinkedList which uses a doubly-linked list, and has a removeLast() method that is O(1) .` 使用java.util.LinkedList可能会更好,该java.util.LinkedList使用双向链表,并且具有removeOast removeLast()方法,该方法为O(1)

No, removing from the end is only applicable to doubly linked lists. 不可以,从结尾删除仅适用于双向链表。 You need the back pointer to put the new NULL terminator on the previous link. 您需要返回指针,以将新的NULL终止符放在上一个链接上。 I suggest making the list doubly linked to fulfil your requirements. 我建议将列表进行双重链接以满足您的要求。

Are you making your own container? 您在制作自己的容器吗? Why not use java.util.LinkedList, which is doubly linked? 为什么不使用双向链接的java.util.LinkedList?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM