Java listIterator()通过.next()和.prev()

时间:2020-04-11 03:41:11

标签: java doubly-linked-list next

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

然后我到达需要对“节点的链接列表”进行排序的地步。由于我是从头开始实现我的链接列表的,因此为了对其进行排序,我也必须为我的链表实现从头开始的“合并排序”,这会花费一些时间。

所以我考虑过将java.util中的“ Java链表”与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)或(到其他功能,而不必传递listIterator()引用来链接我的节点列表。

我应该从头开始坚持我的链接列表,而只编写“合并排序”

1 个答案:

答案 0 :(得分:3)

ListIterator的{​​{3}}解释了此问题。基本上,“当前”位置不是单个节点,而是在两个节点之间。具体来说,它是在调用prev()或调用next()的节点之间。例如,在您对next()的前两次调用之后,迭代器如下所示:

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

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

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

接着,再次调用next()将返回8,依此类推。这是设计使然,您在使用ListIterator遍历时必须考虑到这一点。

相关问题