使用Java中的ListIterator迭代LinkedList元素
ListIterator可用于正向和反向遍历LinkedList中的元素。
在ListIterator中,hasNext( )方法在正向遍历LinkedList时,如果还有更多元素则返回true,否则返回false。next( )方法返回LinkedList中的下一个元素,并向前移动游标位置。
在ListIterator中,hasPrevious( )方法在反向遍历LinkedList时,如果还有更多元素则返回true,否则返回false。previous( )方法返回LinkedList中的前一个元素,并将游标位置向后移动。
下面给出一个演示此功能的程序。
示例
import java.util.ListIterator;
import java.util.LinkedList;
public class Demo {
public static void main(String[] args) {
LinkedList<String> l = new LinkedList<String>();
l.add("Andy");
l.add("Sara");
l.add("James");
l.add("Betty");
l.add("Bruce");
ListIterator li = l.listIterator();
System.out.println("The LinkedList elements in the forward direction are: ");
while (li.hasNext()) {
System.out.println(li.next());
}
System.out.println("
The LinkedList elements in the reverse direction are: ");
while (li.hasPrevious()) {
System.out.println(li.previous());
}
}
}输出
上述程序的输出如下:
The LinkedList elements in the forward direction are: Andy Sara James Betty Bruce The LinkedList elements in the reverse direction are: Bruce Betty James Sara Andy
现在让我们理解一下上面的程序。
创建LinkedList,并使用LinkedList.add()将元素添加到LinkedList中。下面是一个演示此功能的代码片段
LinkedList<String> l = new LinkedList<String>();
l.add("Andy");
l.add("Sara");
l.add("James");
l.add("Betty");
l.add("Bruce");然后使用ListIterator接口正向和反向显示LinkedList元素。下面是一个演示此功能的代码片段
ListIterator li = l.listIterator();
System.out.println("The LinkedList elements in the forward direction are: ");
while (li.hasNext()) {
System.out.println(li.next());
}
System.out.println("
The LinkedList elements in the reverse direction are: ");
while (li.hasPrevious()) {
System.out.println(li.previous());
}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP