给定节点参考,在Java中的LinkedList中删除节点 [英] Remove a node in LinkedList in Java given the node reference

查看:95
本文介绍了给定节点参考,在Java中的LinkedList中删除节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有LinkedList

For example, if I have LinkedList

LinkedList<Integer> ll = new LinkedList<Integer>();
ll.add(1);
ll.add(2);
ll.add(3);
Integer x = new Integer(10);
ll.add(x);
ll.add(4);
// now the list looks like 1->2->3->10->4

// what if I want to remove 10 and I still have the reference to that node x
// what is the API of that
// somethings like ll.remove(x)...

如果我自己实现双向链表,只需

If I implement a doubly linked list by myself, just

currentNode.prev.next = currentNode.next;
currentNode.next.prev = currentNode.prev;

Java的LinkedList实现是否支持此操作?

Does Java's implementation of LinkedList support this operation?

推荐答案

我相信这只是一个复制粘贴错误,您忘记了将节点x添加到链接列表中。假设您的正确代码是这样的:

I believe its just a copy paste error that you forgot to add the node x to your linked list. Assuming your correct code is like this:

Integer x = new Integer(10);
ll.add(x);
ll.add(4);

您可以使用 remove(Object o)方法。因此调用该命令从链接列表 ll 中删除​​节点 x

You can remove a node from java LinkedList using remove(Object o) method. So call that to remove node x from linkedlist ll.

ll.remove(x); //removes x from linkedlist but does not delete object x

它将删除 x 来自链接列表,但对象 x 在代码中仍然有效并且可以在其他任何地方使用。

It will remove x from the linkedlist but object x is still alive in your code and usable anywhere else.

这篇关于给定节点参考,在Java中的LinkedList中删除节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆