英文:
How to get Node-Entry Reference from LinkedList in java
问题
如何从LinkedList中获取对实际Node(entry)对象的引用,而不是其持有的值?
类似于这样:
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> test = new LinkedList<String>();
test.addLast("first");
test.addLast("second");
test.addLast("third");
var thirdNodeReference = test.getLastNode(); // 这样的方法是否存在?
test.addLast("fourth");
var secondNodeReference = thirdNodeReference.previous(); // 执行类似操作。
}
}
在Java LinkedList中是否存在类似LinkedList.getLastNode()
的方法,以便可以在其上执行previous()
或next()
操作?
我知道LinkedList.listIterator()
存在,但它不太有用,因为我将拥有对每个Node(entry)的引用,我需要与它们一起工作,就像上面代码中的lastNodeReference
一样。
如果在JAVA标准库中没有这样的功能,是否有任何第三方(外部)库可以使用?
原因:
我需要访问Node以执行remove()
操作以达到O(1)的时间复杂度。
在实际的JAVA代码实现中,它通过遍历列表来执行此操作,以找到包含给定对象的Node,方法是在其路径上对每个节点执行equals()
。另请参阅此评论。
如果我们直接引用Node对象,这可以在理论上以O(1)的时间复杂度执行 - 因为remove()
只需要更改previous
和next
Node的两个指针。
英文:
How to get the reference to the actual Node (entry) object from LinkedList - Not the value that it holds?
Something like this :
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> test = new LinkedList<String>();
test.addLast("first");
test.addLast("second");
test.addLast("third");
var thirdNodeReference = test.getLastNode(); // Does this even exist ?
test.addLast("fourth");
var secondNodeReference = thirdNodeReference.previous(); // To perform such operations.
}
}
Does there exist a method like LinkedList.getLastNode()
in java LinkedList so that one can perform previous()
or next()
operations on it?
I know LinkedList.listIterator()
exists but that's not useful, because I'll be having references to each Node (entry), and I need to work with them - such as lastNodeReference
in the code above.
If such a functionality doesn't exist in JAVA Standard Library, is there any 3rd party (external) Library that I can use?
Reason:
I need to access the Node to perform remove()
operation in O(1)
.
In the actual JAVA code implementation it performs this in O(N)
by traversing the list to find the Node containing the given object by performing equals()
on every node on it's way. Also, check this comment.
This can be performed ideally in O(1)
if we have a direct reference to Node object - because remove()
only requires a change of 2 pointers of previous
and next
Node.
答案1
得分: 1
有一个 descendingIterator 方法在 LinkedList 上,它被描述为“以相反的顺序返回此双端队列中的元素的迭代器”,虽然不完全清楚 OP(原始问题/提问者)想要什么,迭代器确实具有 .next、.previous 和 .remove 方法。
英文:
There is a descendingIterator method on LinkedList, which is described as Returns an iterator over the elements in this deque in reverse sequential order
, while it isn't (completely) clear what OP wants, Iterator does have a .next, .previous, and .remove methods.
答案2
得分: 0
所以,不,你不能通过链表直接获取前一个元素。
你可能想要实现一个双向链表(在谷歌上很容易找到示例代码)。
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论