LinkedList迭代器作为局部var或参数在递归时没有保存值为什么?

时间:2016-08-21 21:10:18

标签: java recursion

此代码使用递归将Kth打印到LinkedList中的最后一个元素。 LinkedList包含abcdef且k = 4。

预期输出为cdef

通过递归,我想使用本地Iterator来跟踪方法itrLocal中节点kToLast()的位置。但是,我发现itrLocal不是 从递归调用返回时保存。

这是一个错误吗?

import java.util.Iterator;
import java.util.LinkedList;

//with recursion  O(n) space and O(n) time.
public class KthToLast {

    public KthToLast() {
    }

    public static void main(String[] args){

        LinkedList s = new LinkedList();

        s.add("a");
        s.add("b");
        s.add("c");
        s.add("d");
        s.add("e");
        s.add("f");

        KthToLast k = new KthToLast();
        LinkedList resultList= new LinkedList();
        int n = k.kToLast(s.iterator(), 4, resultList);     
    }//main


    private int kToLast(Iterator<String> itr, int k, LinkedList resultList)    {

        Iterator<String> itrLocal = itr;


        if (!itr.hasNext()) {
           return k;

        }
        else {
            String data = (String) itr.next();

            int n=  kToLast(itr,k, resultList)-1;

            if (n >= 0) {
                resultList.add(data);
            }
            if (n==0){
                Iterator reverse = resultList.descendingIterator();
                while (reverse.hasNext()){
                    System.out.print(reverse.next());
                }//if



            //value of data is reserved for each recursion
            if  (n >= 0) {

            /* why would itrLocal change with itr ? itrLocal at each  
               recursion call was not reserved.   is this a bug ?
             */
              while (itrLocal.hasNext()){
                  System.out.println(itrLocal.next());
              }               
            }//if           
            return n;           
        }//else             
    }//ktolast
}//class

0 个答案:

没有答案