我需要遍历此自定义linked list implementation并显示其内容:
我能够通过for循环很容易地从头到尾显示列表内容:
for (AccountRecordSerializable account : list) {
System.out.println(account);
}
一切正常。现在我试图改变这一点。在提供的LinkedList类中使用其中也包含LinkedListIterator类。迭代器类有hasNext()
,hasPrevious()
这样的方法,我知道可以这样做,但我不太确定如何通过我的LinkedList使用该迭代器来实现。
有没有比以前更简单的方法来扭转这种情况?或者我如何使用Iterator类迭代我的列表以便它执行任务?
如果这没有任何意义,我道歉...如果您需要澄清,请告诉我。谢谢。
答案 0 :(得分:1)
单链表并不意味着从头到尾遍历。你有几种选择
答案 1 :(得分:1)
Java LinkedList实现了提供方法Deque的接口descendingIterator。
以相反的顺序返回此双端队列中元素的迭代器。元素将从最后(尾部)到第一个(头部)按顺序返回。
我的建议是在你的类中实现这些接口,并获得反向迭代器。
linked list是具有一些属性的数据结构,您应该使用这些属性来实现。链表的典型结构是元素指向下一个元素。在您的情况下,您有实现支持双链表。
private int size = 0; // size can never be < 0
private DLNode<E> head;
private DLNode<E> tail;
在您的代码中,您有DLNode
代表双链接节点。这意味着您可以使用head
从tail
移至hasNex()
,并使用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
和public <T> reversePrint(Deque deque) {
for (Iterator<T> iterator = deque.descendingIterator(); iterator .hasNext();){
System.out.println(iterator .next());
}
}
不属于类。与主要相同。
如果你有标准的Java LinkedList,你可以这样写:
{{1}}
缩小迭代器的范围,促进循环而不是while。
答案 2 :(得分:1)
我决定通过将光标分配到列表的末尾并使用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;
}
}
我确信有更漂亮的方式来编写它,但它现在已经实现了它的目的。
答案 3 :(得分:0)
使用.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());
}