'How come i can't add all the nodes from Stack
Stack<Node> stack = new Stack<>();
for (int i = 0; i < 10; i++) {
stack.push(new Node(i));
}
when i try:
while(stack != null){
double_list.add_tail(stack.pop());}
it throws me EmptyStackException
when I try this:
for (int i = 0; i < stack.size(); i++) {
double_list.add_tail(stack.pop());
}
it does not print out all the nodes(only half of them)
Solution 1:[1]
The first example is wrong because you're comparing the stack reference to null, but you mean to check its size:
// Wrong
while(stack != null){
double_list.add_tail(stack.pop());
}
// Right
while(stack.size() > 0) {
double_list.add_tail(stack.pop());
}
This is because even when the stack is empty, the reference to the empty structure still exists and isn't null.
The second example is wrong because you're popping from the stack inside your loop, so its size is shrinking:
// Wrong
for (int i = 0; i < stack.size(); i++) {
double_list.add_tail(stack.pop());
}
// Right
int length = stack.size();
for (int i = 0; i < length; i++) {
double_list.add_tail(stack.pop());
}
Without this change, stack.size() is evaluated after the pop(), so it will be one element smaller. Meanwhile, i is incremented. The first iteration compares i=0 to stack.size()=10, the next i=1 to stack.size()=9 and so on. It stops when i=5 and stack.size()=5. Setting length=stack.size(); before the loop fixes length to 10 regardless of future changes to stack.size().
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Welbog |
