This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I have taken a test which contains some interesting questions, such as how to use a single queue to re-arrange some number The queue contains some numbers that are 5,6,8,4,2 then after using some methods,then the arrangement becomes-->2,4,8,6,5. The constraint is that you can use a variable to do it but not array. Of course, I solved the problem but I wonder if any ranchers have any other idea to solve above question. ^o^ And I would be appreciate if any ranchers provide some interesting algorithm that can be used to change a stack to become a queue or to change a data structure to become another type of data structure. It would be better if you could provide JAVA programming language. (C or C++ also fine, but not c# ) thanks for your help [ November 17, 2004: Message edited by: siu chung man ]
Oo...I create another unclear question My question is not related to sorting , as I mentioned before, one of the data structure used to store some numbers, how to implement some algorithms in order to change queue to another data structure. For example, a queue is used to store some numbers 5,6,8,4,2, which algorithm is used to change the arragement to be 2,4,8,6,5. You can not use a stack to do it. Another example is that a stack stores some numbers 5,6,8,4,2, which algorithm is used to change the arragement to be 2,4,8,6,5, you can not use another stack to do. Both of these example can only use a variable to do it. Any suggestion and idea is appreciate. thanks
The problem is to reverse the contents of the queue. Are there additional constraints on the problem imposed by the fact that this is a queue? In other words, is it a proper queue from which you can only access the first element? Or perhaps a double-ended queue, where you can look at the element at either end? Or is it random access?
yes, it is a proper queue from which we can only dequeue from the front (first element) and enqueue to the back(rear). It is not a double-ended queue. We can use a variable(but not array) as a temporary variable to store an element. Ernest thanks for your help
In two minutes recursion is the only solution using a single temporary variable that pops into my head. Of course, by using recursion you're actually using one temporary variable per element in the queue, so that's kind of cheating (it acts like an open-ended array stretched out across the program stack).
However, I would not say that using an algorithm like this "makes a queue behave like a stack." That would be akin to using Collections.sort(list) and then claiming that a list acts like a sorted list.