如何创建从列表末尾开始的列表迭代器

时间:2014-03-07 23:40:47

标签: java list iterator listiterator

我有一个家庭作业问题,要求我创建一个从列表末尾开始的列表迭代器。我不知道该怎么做。这是代码

public class LinkedListTester7
{
    public static void main(String [] args)
    {
        LinkedList<Integer> list = new LinkedList<Integer>();
        for (int i = 0 ; i < 100 ; i = i + 2)
            list.add(i) ;
        //-----------Start below here. To do: approximate lines of code = 3
        // 1. make a list iterator that starts at the end of the list ;
        ListIterator<Integer> litr = list.listIterator();
        //2.  while hasPrevious ;
        while (litr.hasPrevious()) {
            //3. print what is returned by previous() followed by a blank without a newline  
            System.out.println(litr.previous()+ " ");
        }
        //-----------------End here. Please do not remove this comment.     Reminder: no changes outside the todo regions.
        System.out.println() ;
    }
}

3 个答案:

答案 0 :(得分:3)

阅读java.util.List API文档......

ListIterator<Integer> litr = list.listIterator(list.size());

答案 1 :(得分:0)

实际上是 A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next().

如果你想第一次调用next()/ previous()来返回最后一个元素你可以使用listIterator(int index)并传递它list.size() - 1如果你想迭代前进或list.size ()如果你想向后迭代。

答案 2 :(得分:-2)

我认为这可能是您正在寻找的代码:

for (int i = litr.size(); i >= 0; i--) {
    System.out.println(litr.get(i));
}

基本上它从数组的末尾开始,并从最后到第一个打印结果。

这是从ArrayList的END开始的:

i = litr.size();

i--在数组中向后计数直到达到0。