我需要遍历这个自定义链表实现并显示其内容:
- 从头到尾
- 然后又从尾部到头部
我能够通过for循环非常容易地从头到尾显示列表内容:
for (AccountRecordSerializable account : list) {
System.out.println(account);
}
一切都很好。现在我正试图扭转这种局面。在提供的要使用的LinkedList类中,该类内部也有一个LinkedListIterator类。迭代器类有hasNext()
、hasPrevious()
等方法,我知道这些方法可以用来实现,但我不太确定如何通过LinkedList使用迭代器来实现
有没有比我以前做的更简单的方法来扭转这种局面?或者,我将如何使用Iterator类来遍历我的列表,以便它执行任务?
如果这没有任何意义,我道歉。。。如果你需要澄清,请告诉我。。谢谢
以相反的顺序返回该deque中元素的迭代器。元素将按从最后一个(尾部)到第一个(头部)的顺序返回。
我的建议是在类中实现该接口,并获得反向迭代器。
链表是具有一些属性的数据结构,您应该使用这些属性来获取实现。链表的典型结构是一个元素指向下一个元素。在您的案例中,您有一个支持双链表的实现。
private int size = 0; // size can never be < 0
private DLNode<E> head;
private DLNode<E> tail;
在您的代码中,您有DLNode
,代表Double Linked Node。这意味着您可以使用hasNex()
从head
移动到tail
,使用hasPrevious()
从尾部移动到头部。
在你的类中,你有LinkedListIterator
类,你可以用这种方法获得:
public ListIterator<E> listIterator(int index) {
if ((index < 0) || (index > size)) {
throw new IndexOutOfBoundsException("index " + index+ " is out of range: 0 to " + size);
}
return new LinkedListIterator<E>(index);
}
所以要打印你的元素,你可以这样做。
public <T> void printLinkedListFromHead(LinkedList<T> list) {
for(ListIterator<T> iterator = list.listIterator(0); iterator.hasNext();) {
System.out.println(iterator.next());
}
}
您还应该为代码创建一个单独的类,将上下文中不属于链表实现的代码放在该类中。方法readObjects
和writeObjects
不属于类。与main相同。
如果你有标准的Java链接列表,你可以写这样的东西:
public <T> reversePrint(Deque deque) {
for (Iterator<T> iterator = deque.descendingIterator(); iterator .hasNext();){
System.out.println(iterator .next());
}
}
为了缩小迭代器的作用域,promote for循环比while要小。
单链表并不意味着从尾部遍历到头部。有几个选项
- 反转链表并从头到尾遍历(对于原始链表,这将是从头到尾的遍历)
- 有一堆。遍历链表并将元素放入堆栈中。然后继续从堆栈中弹出元素并打印
我决定向后遍历,将光标放在列表的末尾,并使用get(index)
迭代,然后递减。这就是我所拥有的:
System.out.println("Tail to Head");
for (int i = list.size - 1; list.get(i) != null; i--) {
System.out.println(list.get(i));
if (i == 0 ){
break;
}
}
我相信有更漂亮的方法来写它,但它现在实现了它的目的。
使用.descendingIterator()
将执行您想要的操作:)
示例:
LinkedList<Integer> linkedList = new LinkedList<Integer>();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
Iterator<Integer> iterator = linkedList.descendingIterator();
while (iterator.hasNext())
{
System.out.println(iterator.next());
}
如果要保存已反转的新LinkedList。。仅
LinkedList<Integer> linkedList = new LinkedList<Integer>();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
Iterator<Integer> iterator = linkedList.descendingIterator();
LinkedList<Integer> reversed = new LinkedList<Integer>();
while (iterator.hasNext())
{
reversed.add(iterator.next());
}