Hi,
New to java and trying a stack problem below. Rather have the answer to my question than a solution if possible because I'll keep having the same problem, hope it makes sense;
Write a method reorder that takes a queue of integers as a parameter and that puts the integers into sorted (nondecreasing) order assuming that the queue is already sorted by absolute value. For example, suppose that a variable called q stores the following sequence of values:
front [1, 2, -2, 4, -5, 8, -8, 12, -15, 23] back
Notice that the values appear in sorted order if you ignore the sign of the numbers. The call of reorder(q); should reorder the values so that the queue stores this sequence of values:
front [-15, -8, -5, -2, 1, 2, 4, 8, 12, 23] back
Notice that the values now appear in sorted order taking into account the sign of the numbers. You may use one stack as auxiliary storage to solve this problem.
This is my code (not the best or even correct but....);
import java.util.Queue;
import java.util.Stack;
public class Reorder {
public static void main(args[] String) {
}
public static void reorder2(Queue<integer> q) {
Stack<integer> s = new Stack<integer>();
for (int i = 0; i < q.size(); i++) {
int smaller = q.remove();
if (smaller < q.remove()) {
s.push(smaller);
}
q.add(q.remove());
if (smaller > q.remove()) {
s.push(q.remove());
}
q.add(smaller);
}
while (!s.isEmpty()) {
q.add(s.pop());
}
}
}
Correct result is; [-15, -8, -5, -2, 1, 2, 4, 8, 12, 23]
My results is [1, -5, -15, -8, -2, -8]
What happened to 2, 4, 8, 12, 23? These numbers should be added back to the queue and compared with q.remove(). Then they should be added to stack eventually but they disappear somehow!?
Thanks