Hi guys, Finally I've registered after being a very long visitor for this awesome community.
I have this problem which consumed 2 days of my time trying to figure out how to solve it. And your help is needed guys.
The problem says: Transfer elemenents from Stack1 to Stack2 , without using additional stack, recursion or arrays. Only using some additional variables. Stack2 should have the same order as in Stack1.
what I understand from the word "Transfer" , this is going to be a desructive copy operation, because stack1 will be empty.
My attempt does not work for any stack size. The snippet below for a 3 elements stack and it works fine. Some guy gave me a hint to use 2 loops and an if statement to make it working for any size. But I failed. I don't know how exactly this could work.
public static void stackSwitch(Stack stack1){
Stack stack2 = new Stack();
Object top = stack1.topEl();
//save the top
top = stack1.pop();
stack2.push(stack1.pop());
stack2.push(stack1.pop());
//push it back
stack1.push(top);
stack1.push(stack2.pop());
stack1.push(stack2.pop());
//save the top
top = stack1.pop();
stack2.push(stack1.pop()); // The bottom is left in Stack1
stack2.push(top);
stack1.push(stack2.pop());
stack1.push(stack2.pop());
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
System.out.println(stack1.toString());
System.out.println(stack2.toString());
}