java - Am I doing this recursively or would this be considered iteration? -
public t get(int i) { if(i == 0 ){ t val = cur.getdata(); cur = head; return val; } else{ cur = cur.getnext(); return get(i-1); } } // have solve recursively , cant use iteration, using iteration
am doing recursively or considered iteration?
your function calling itself:
public t get(int i) { if(i == 0 ){ t val = cur.getdata(); cur = head; return val; } else{ cur = cur.getnext(); return get(i-1); // <============ here } } by definition, that's recursion, not iteration.
iteration this:
public t get(int i) { t val = cur.getdata(); while (i-- > 0) { cur = cur.getnext(); val = cur.getdata(); } cur = head; return val; } there, loop within get, don't have call itself. it's not perfect translation of recursive example, because handles things bit differently if i negative start with, meets intent (both versions use kind of guard protect against i being negative start with).
Comments
Post a Comment