iterator - java: implementing binary search tree and overriding iterable -


i want able use each loop end in infinite loop.
i'm not using recursion , debugger not giving me hints. if is, i'm not getting it.

here's tester:

    student stud1 = new student("nic", "aichael", "1234", 75, 90);     student stud2 = new student("nic", "bichael", "1234", 75, 90);     student stud3 = new student("nic", "cichael", "1234", 75, 90);     student stud4 = new student("nic", "dichael", "1234", 75, 90);     avlpersontree tree = new avlpersontree();     tree.add(stud1);     tree.add(stud2);     tree.add(stud3);     tree.add(stud4);     for(node node: tree){         node.tostring();      } 

here avlpersontree class:

    public class avlpersontree implements iterable<node>{ private node root; private int size;  public avlpersontree(){     super();     root = null; }  public void add(person newperson){     node newnode = new node(newperson);     if(root == null){         root = newnode;     }else{         root.addnode(newnode);     }     size++; }  public int size(){     return size; }   @override public iterator iterator() {     iterator<node> iterate = new iterator(){          @override         public boolean hasnext() {             if(root == null){                 return false;             }             if(root.getleftnode() == null && root.getrightnode() == null){                 return false;             }             return true;         }          @override         public node next() {             if (!hasnext()) {                 throw new java.util.nosuchelementexception("no more elements");             }             return preordernext();             }          @override         public void remove() {             throw new unsupportedoperationexception("not supported yet."); //to change body of generated methods, choose tools | templates.         }      };     return iterate; }  private node preordernext() {     stack<node> visiting = new stack<>(); if (visiting.empty()) { // @ beginning of iterator     visiting.push(root); } node node = visiting.pop(); // need visit left subtree first, right // since stack lifo, push right subtree first, // left.  push non-null trees if (node.getrightnode() != null) {     visiting.push(node.getrightnode()); } if (node.getleftnode() != null) {     visiting.push(node.getleftnode()); } // may not have pushed anything.  if so, @ end if (visiting.empty()) { // no more nodes visit     root = null; } return node; } 

}

your "preordernext" function wrong.

the 5 line @ begening bring "root" in "node"

stack<node> visiting = new stack<>(); if (visiting.empty()) { // @ beginning of iterator visiting.push(root); } node node = visiting.pop(); 

so never iterating , node forever "root"


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -