I think there are several problems with your code:
- 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.
- 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);
}