原文: https://beginnersbook.com/2014/08/iterate-a-linkedlist-in-reverse-sequential-order-java/

描述

使用 LinkedList 类的 descendingIterator()方法以相反的顺序迭代链表的程序。

程序

  1. import java.util.LinkedList;
  2. import java.util.Iterator;
  3. class LinkedListDemo {
  4. public static void main(String[] args) {
  5. // create a LinkedList
  6. LinkedList<String> list = new LinkedList<String>();
  7. // Adding elements to the LinkedList
  8. list.add("Element1");
  9. list.add("Element2");
  10. list.add("Element3");
  11. list.add("Element4");
  12. // Displaying LinkedList elements
  13. System.out.println("LinkedList elements: "+list);
  14. /* public Iterator<E> descendingIterator(): Returns an
  15. * iterator over the elements in this list in reverse
  16. * sequential order. The elements will be returned in
  17. * order from last (tail) to first (head).
  18. */
  19. Iterator it = list.descendingIterator();
  20. // Displaying list in reverse order
  21. System.out.println("Elements in Reverse Order:");
  22. while (it.hasNext()) {
  23. System.out.println(it.next());
  24. }
  25. }
  26. }

输出:

  1. LinkedList elements: [Element1, Element2, Element3, Element4]
  2. Elements in Reverse Order:
  3. Element4
  4. Element3
  5. Element2
  6. Element1