Reputation: 11
I have a question, about using Stack with Java.
Let's say I have three stacks
Stack<Integer> stack1 = new Stack<Integer>();
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?
Upvotes: 1
Views: 526
Reputation: 597116
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:
List
or an array)Collections.sort(..)
or Arrays.sort(..)
)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.
Upvotes: 3
Reputation: 26819
This problem is called: the Tower of Hanoi problem, try find code/description for this in wikipedia/google.
Upvotes: 1
Reputation: 12006
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));
Upvotes: 0