I'm getting a Stack overflow error for the following method at the recursive call. I think I need to make it iterative in order for it to work. How would I write the following method iteratively?
Node myMethod(String foo, Node p) {
if(p == null) {
p = new Node(foo);
p.link = spot;
spot = p;
p.calc[bar] = 1;
return p;
} else if(foo.equals(p.origin)) {
p.calc[bar] = p.calc[bar] + 1;
return p;
} else {
while (p.next == null & foo.equals(p.origin)){
p = p.next;
}
p.next = myMethod(foo, p.next);
return p;
}
}
p is a Node class that has String foo, String origin, Node link, Node next, and int Array calc[]. bar is an int. spot is a random node.
This is what I have tried so far
Node myMethod(String foo, Node p) {
if(p == null) {
p = new Node(foo);
p.link = spot;
spot = p;
p.calc[bar] = 1;
return p;
} else if(foo.equals(p.origin)) {
p.calc[bar] = p.calc[bar] + 1;
return p;
} else {
while (p.next == null & foo.equals(p.origin)){
p = p.next;
}
//instead of doing recursion on: p.next = myMethod(foo, p.next);. I tried the following:
if (p.next == null){
p.next = new Node(foo);
p.next.link = spot;
spot = p.next;
p.next.calc[bar] = 1;
} else if (foo.equals(p.next.origin)){
p.next.calc[bar] = p.next.calc[bar] + 1;
} else {
while (p.next.next == null & foo.equals(p.next.origin)){
p.next = p.next.next;
}
}
}
return p;
}
myMethodtells us nothing about the purpose of this method...while (p.next == null & foo.equals(p.origin)? It does not appear that you intended to operate bitwise.&with&&but I'm still getting the Stack Overflow error.