java - Writing your own Iterator for a LinkedList -
i have written iterator arraylist, need write 1 linkedlist. suggestions on how make code more efficient??
public class mylinkedlistiterator<t> implements iterator<t> { //the list on iterating private mylinkedlist<t> list; private int curpos; public mylinkedlistiterator(mylinkedlist<t> list) { this.list = list; curpos = 0; } @override public boolean hasnext() { return curpos < list.size(); } @override public t next() { t element = list.get(curpos); curpos++; return element; } }
incase helpful, here listnode class keeps track of pointers on linkedlist
public class listnode<t> { private t value; private listnode<t> next; public listnode(t value, listnode<t> next) { this.value = value; this.next = null; } public listnode(t value) { this(value, null); } public t getvalue() { return value; } public listnode<t> getnext() { return next; } public void setnext(listnode<t> next) { this.next = next; } }
i lost on go, appreciate help
after looking @ mylinkedlistiterator changed hasnext method this
public boolean hasnext() { return list.getnext()==null ? false:true; }
and added getcurrent method current element list
public t getcurrent(){ return (t)list; }
and final code looks this
public class mylinkedlistiterator<t> implements iterator<t> { //the list on iterating private mylinkedlist<t> list; public mylinkedlistiterator(mylinkedlist<t> list) { this.list = list; } @override public boolean hasnext() { return list.getnext()==null ? false:true; } @override public t next() { t element = (t)list.getnext(); list = (mylinkedlist)element; return element; } public t getcurrent() { return (t)list; } public static void main(string[] args) { mylinkedlist<integer> m =new mylinkedlist(new integer(10)); mylinkedlist<integer> m1 =new mylinkedlist(new integer(11)); mylinkedlist<integer> m2 =new mylinkedlist(new integer(12)); mylinkedlist<integer> m3 =new mylinkedlist(new integer(13)); m.setnext(m1 ); m1.setnext(m2 ); m2.setnext(m3 ); mylinkedlistiterator<mylinkedlist<integer>> =new mylinkedlistiterator(m); system.out.println(((mylinkedlist)it.getcurrent()).getvalue()); while(it.hasnext()){ system.out.println(((mylinkedlist)it.next()).getvalue()); } } }
attached running main method reference. hope may help.
Comments
Post a Comment