【问题标题】:How to make a list iterator that starts at the end of the list如何制作从列表末尾开始的列表迭代器
【发布时间】:2014-03-07 23:40:46
【问题描述】:

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

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() ;
    }
}

【问题讨论】:

    标签: java list iterator listiterator


    【解决方案1】:

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

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

    【讨论】:

    • 对不起,我对使用 Java 还很陌生。谢谢!
    【解决方案2】:

    其实是 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()如果你想向后迭代。

    【讨论】:

      【解决方案3】:

      我认为这可能是您要查找的代码:

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

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

      这是从 ArrayList 的 END 开始的内容:

      i = litr.size();
      

      i-- 在数组中倒数直到达到 0。

      【讨论】:

      • 他在询问一个链表,通过索引访问它是个坏主意
      猜你喜欢
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-25
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      相关资源
      最近更新 更多