【发布时间】:2020-07-23 21:13:22
【问题描述】:
我一直在从事一个项目,我从头开始使用单独的“节点类”实现了一个(双向链接列表)。
然后我已经到了需要对“节点链接列表”进行排序的地步。由于我从头开始实现了我的链表,所以为了对其进行排序,我也必须从头开始为我的链表实现“合并排序”,这有点费时。
所以我考虑使用 java.util 中的“Java Linked List”和 listIterator(),然后使用 Collections.sort() 对我的 LinkedList 进行排序,但是它的 next() 和 previous() 给了我一些意想不到的奇怪输出与我使用 (.next) & (.prev) 直接访问节点的 LinkedList 时相比。例如,假设:
node1.time = 7;
node2.time = 8;
node3.time = 9;
node4.time = 10;
LinkedList<Node> nodeList = new LinkedList<Node>():
nodeList.add(node1); nodeList.add(node2); nodeList.add(node3); nodeList.add(node4);
void testFunction() {
ListIterator<Node> nodesIterator = nodeList.listIterator();
Node current;
for (int i = 0; i < 2; i++) {
current = nodesIterator.next();
System.out.println("current = " + current.time);
}
System.out.println("outside of loop:");
System.out.println("move current backward:");
current = nodesIterator.previous();
System.out.println("current = " + current.time);
System.out.println("move current forward:");
current = nodesIterator.next();
System.out.println("current = " + current.time);
System.out.println("Passing nodesIterator into testFunction2():");
testFunction2(nodesIterator);
}
void testFunction2(ListIterator<Node> nodesIterator) {
System.out.println("inside testFunction2():");
Node current = nodesIterator.next();
System.out.println("current = " + current.time);
System.out.println("move current backward:");
current = nodesIterator.previous();
System.out.println("current = " + current.time);
System.out.println("move current backward again:");
current = nodesIterator.previous();
System.out.println("current = " + current.time);
}
输出:
current = 7
current = 8
outside of loop:
move current backward:
current = 8
// -> current is suppose to be 7 if previous current inside the loop was 8?
move current forward:
current = 8
// -> current is suppose to be 9 if previous current = 8?
Passing nodesIterator into testFunction2():
inside testFunction2():
current = 9
// -> guess it's correct since previous current = 8?
move current backward:
current = 9
// -> suppose to give me 8 since previous current = 9?
move current backward again:
current = 8
// -> now it actually moved backward!
Java 的 next() 和 prev() 是怎么回事?我从头开始实现的链接列表永远不会给我这些问题,而且通过直接访问 (.next) 和 (.prev) 将节点传递给其他函数进行遍历更简单,因为我可以传入 (node.next) 或 ( node.prev) 到其他函数,而无需传入 listIterator() 引用来链接我的节点列表。
我是否应该从头开始使用我的链接列表,只编写“合并排序”代码
【问题讨论】:
-
How much research effort is expected of Stack Overflow users? 中写道:在 Stack Overflow 上提问应该是您寻找答案过程中的最后一步我在 Google 上搜索了这些术语 java linkedlist listiterator 发现Java LinkedList ListIterator behavior 没有回答你的问题吗?
-
@Abra 感谢您的参考。在我提出问题之前,我确实在谷歌上搜索了有关 java linkedlist listiterator 的更多信息,但不知何故无法找到您指出的链接
标签: java doubly-linked-list next