0

If there are an odd number of values in the stack, the value at the top of the stack is not moved.

What's wrong..?

public static void switchPairs(Stack<Integer> st){
    Queue<Integer> q = new LinkedList<Integer>();
    int size = st.size();
    
    for(int i = 0; i < size; i++){
        
        int a = st.pop();
        int b = st.pop();
        q.add(a);
        q.add(b);
    }
}
Melquiades
  • 8,496
  • 1
  • 31
  • 46
bazookyelmo
  • 103
  • 1
  • 9
  • What do you think is wrong? You are always operating with pairs, where should the last value go? This should give you exceptions because the stack is empty after a few iterations. – Sotirios Delimanolis Feb 25 '14 at 23:28

1 Answers1

1

I think there are several problems with your code:

  1. You should go until size/2. You're pop-ing twice in each iteration. Then check if the length was odd and just add the last remaining element if so.
  2. I think that your code only reverses your stack.

This is not tested but i think it should look something like this (also took the liberty to get rid of some useless variables - performance probably isnt an issue in this case).

Make your method return a stack and use it like this:

st = switchPairs(st);

And the method's body:

public Stack<Integer> switchPairs(Stack<Integer> st){
        Stack<Integer> q = new Stack<Integer>();   
        for(int i = 0; i < st.size()-1; i++){        
            q.push(st.elementAt(i+1));
            q.push(st.elementAt(i++)));
         }
         if(st.size()%2==1){
            q.push(st.pop());
         }
         return q;
}

To keep it void (usage taken from Here)

AtomicReference<Stack<Integer>> ref = new AtomicReference<Stack<Integer>>(st);
switchPairs(ref);
st = ref.get();

And the method's body:

public void switchPairs(AtomicReference<Stack<Integer>> ref){
        Stack<Integer> q = new Stack<Integer>();   
        for(int i = 0; i < ref.get().size()-1; i++){        
            q.push(ref.get().elementAt(i+1));
            q.push(ref.get().elementAt(i++)));
         }
         if(ref.get().size()%2==1){
            q.push(ref.get().pop());
         }
         ref.set(q);
}
Community
  • 1
  • 1
Florin Bombeanu
  • 850
  • 2
  • 11
  • 23