在中间和末尾删除节点

时间:2016-02-21 21:22:33

标签: java pointers linked-list nodes

我只是想知道以下是否是正确的方法来删除链接列表中特定位置的节点。

So if my "target" node is located between the head and the tail (middle):
1. set a "curr" node equal to the head
2. Iterate using "curr = curr.next" until curr.next = "target"
3. set curr.next = curr.next.next 

If my target is located at the tail I do:
1. set "curr" node equal to the head
2.Iterate until curr.next.next = null 
3. set curr.next = null

我也很难理解如何改变" curr"节点i设置等于" head"可以修改与" head"相关联的实际链接列表。而不只是附加到" curr"。

的链接列表

谢谢,我真的需要帮助:)

1 个答案:

答案 0 :(得分:0)

curr引用链接列表中的实际链接,而不仅仅是它们的副本,因此修改curr也会修改LinkedList。这是因为所有java对象都是通过引用传递的。

顺便提一下,我认为区分最后一项的正确方法应该是:

  1. 设置“curr”节点等于头
  2. 使用“curr = curr.next”迭代,直到curr.next .value 等于 target
  3. 如果找到了目标(如果目标不在列表中,前一个循环实际上失败了)

    3.1。如果curr.next是最后一项:curr.next = null

    3.2。 else curr.next = curr.next.next

  4. 此算法更类似于真实的链接列表,因为通常您不会事先知道目标链接是否是最后一个(或者即使它在列表中)