Page 1 of 1

For loops and Stacks

Posted: Sat Apr 25, 2009 8:04 pm UTC
by yitriana
Why don't for loops work on stacks?

==
I am to make a program that collapses integers of a stack.

Write a method collapse that takes a stack of integers as a parameter and that collapses it by replacing each successive pair of integers with the sum of the pair. For example, suppose a stack stores these values:

bottom [7, 2, 8, 9, 4, 13, 7, 1, 9, 10] top

collapsed, it is

bottom [9, 17, 17, 8, 19] top

If the stack stores an odd number of elements, the final element is not collapsed. For example, the stack:

bottom [1, 2, 3, 4, 5] top

Would collapse into:

bottom [3, 7, 5] top

==

i tried using a for loop to run through the stack. why won't it work?

Code: Select all

public void collapse (Stack<Integer> s) {
   Queue<Integer> q = new LinkedList<Integer>();
   for (int i = 0; i < s.size(); i++)   
      q.enqueue(s.pop());   
   while (!q.isEmpty())
      s.push(q.dequeue());
   while (!s.isEmpty())
      q.enqueue(s.pop());   
   while (q.size() > 1)
      s.push(q.dequeue() + q.dequeue());
   if (!q.isEmpty())
      s.push(q.dequeue());   
}

==

however, if i use a while loop inplace of the for loop

Code: Select all

   while(!s.isEmpty())   
      q.enqueue(s.pop()); 


the program works.

Why doesn't a for loop work on the stack?

Re: For loops and Stacks

Posted: Sat Apr 25, 2009 8:19 pm UTC
by Berengal
Finding the answer is simple: Just step through the execution using a debugger.

Re: For loops and Stacks

Posted: Sat Apr 25, 2009 10:25 pm UTC
by 0xBADFEED
The for loop is doing something different than the while loop.

Think about it. The index of the for loop is increasing while the size of the stack is decreasing. What's your loop condition? What happens?

Re: For loops and Stacks

Posted: Thu Apr 30, 2009 1:43 am UTC
by GalstafSofL
for loops do work, you just have to construct them properly. you have a slight bug in your loop, and when you realize it you will slap yourself in the face. the poster above me explained the bug about as well as possible without outright fixing the code.