Java moving number between stacks
I have a question, about using Stack with Java.
Let's say I have three stacks
Stack<Integer> stack1 = new Stack<Integer&开发者_Go百科gt;();
Stack<Integer> stack2 = new Stack<Integer>();
Stack<Integer> stack3 = new Stack<Integer>();
stack1.push(10);
stack1.push(5);
stack1.push(25);
stack1.push(2);
stack1.push(100);
I want these numbers in order from high to low in stack3. So stack3 likes like 100, 25, 10, 5, 2
What would be the best method of moving the number between the stacks?
Due to some bad design decisions in Java, it is possible to make Collections.sort(stack1)
and then simply pop out of the first stack and push into the 2nd.
But note that since Java 6 it is preferable to use ArrayDeque
(or another Deque
) instead of Stack
. With a stack that is not a List
, the sequence would be:
- Take them all out of the first stack (in a
List
or an array) - Sort them (
Collections.sort(..)
orArrays.sort(..)
) - Push them in order into the other stack
But these all java "hacks". If it is a homework problem it is more likely that they want you to implement something like the "Towers of Hanoi" problem, as noted by smas.
This problem is called: the Tower of Hanoi problem, try find code/description for this in wikipedia/google.
Re-phrasing Bozho's answer:
Stack<Integer> stack3 = new Stack<Integer>();
Integer[] arr = stack.toArray(new Integer[stack.size()]);
Arrays.sort(arr);
stack3.addAll(Arrays.asList(arr));
精彩评论