首页 > 解决方案 > Java listIterator() 用 .next() 和 .prev() 给我奇怪的输出

问题描述

我一直在从事一个项目,在该项目中我使用单独的“节点类”从头开始实现了一个(双向链表)。

然后我已经到了需要对“节点链接列表”进行排序的地步。由于我从头开始实现了我的链表,所以为了对其进行排序,我也必须从头开始为我的链表实现“合并排序”,这有点费时。

所以我考虑使用 java.util 中的“Java Linked List”和 listIterator() 然后使用 Collections.sort() 对我的 LinkedList 进行排序,但是它的 next() 和 previous() 给了我一些意想不到的奇怪输出,而不是当我正在使用(.next)和(.prev)直接访问我的节点链表。例如,假设:

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() 引用来链接我的节点列表。

我是否应该从头开始使用我的链接列表并只编写“合并排序”

标签: javadoubly-linked-listnext

解决方案


文档解释ListIterator了这个问题。基本上“当前”位置不是单个节点,它位于两个节点之间。prev()具体来说,它位于您调用或调用时将返回的节点之间next()。例如,在您对next()迭代器的前两次调用之后,如下所示:

7 -> 8 *->* 9 -> 10电流介于8和之间9

调用prev()将返回上一个节点,即8. 然后,迭代器将如下所示:

7 *->* 8 -> 9 -> 10电流介于7和之间8

接下来,再次调用next()将返回8,依此类推。这是设计使然,您在使用ListIterator.


推荐阅读