此代码使用递归将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