Billy
Billy

Reputation: 11

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>();
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

Answers (3)

Bozho
Bozho

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:

  1. Take them all out of the first stack (in a List or an array)
  2. Sort them (Collections.sort(..) or Arrays.sort(..))
  3. 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.

Upvotes: 3

lukastymo
lukastymo

Reputation: 26819

This problem is called: the Tower of Hanoi problem, try find code/description for this in wikipedia/google.

Upvotes: 1

Victor Sorokin
Victor Sorokin

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

Related Questions