this code prints Kth
to the last element in the LinkedList
using recursion. With LinkedList
containing abcdef
and k=4.
The expected output is cdef
With recursion, I wanted to use a local Iterator
to trace the position of the node, itrLocal
in method kToLast()
. But, I found that itrLocal
was not
saved when returned from the recursive call.
Is this a bug ?
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