问题
I have two stacks(which follows LIFO). I would like to know if i can write a C program to use these two stacks work like a queue(FIFO).
回答1:
One stack is used to insert new elements into the queue. The other stack is used to remove elements. When the output stack is empty, the input stack is reversed and becomes the new output stack.
In pseudo-C:
typedef struct { stack in, stack out } queue.
void insert(queue *q, void *data) {
push(q->in, data);
}
void* remove(queue *q) {
if (empty(q->out)) {
while (!empty(q->in)) { // q->out = reversed q->in
push(q->out, pop(q->in));
}
}
return pop(q->out); // assumes that it returns NULL if q->out is empty
}
This is asymptotically the same complexity as a regular queue, but each element is touched several times. Since you're working in C, why not use a regular ring-buffer?
Edit: This is indeed the way Okasaki's functional queues work that @bdonlan's answer mentioned.
回答2:
One such technique is described in:
Chris Okasaki (1995). Simple and efficient purely functional queues and deques. Journal of Functional Programming, 5, pp 583-592
Fulltext is available in postscript format. This technique is described in terms of functional programming, but there is no fundamental reason why you could not implement it in C as well.
回答3:
(Why not just use a queue?)
Basically you use one stack B to reverse the order of the elements in an other stack B, by popping all elements from A and pushing them into B. When you are done, the first object that you will pop from B would be the first that you pushed into the original A.
If you push the elements 1, 2, 3, 4
into A in this order, you'll get:
A: 1, 2, 3, 4 (top)
Pop everything and push into B:
B: 4, 3, 2, 1 (top)
If you start popping B, you'll get in order:
1, 2, 3, 4
The compound operation is a FIFO-like structure. However, it has none of the flexibility of a proper FIFO, since it only works in passes. It might be useful in code for low-end microcontrollers where implementing a heap is an issue, but you should not use stacks like that on any modern (i.e. post 1980) computer.
来源:https://stackoverflow.com/questions/4906050/how-can-i-use-two-stackslifo-so-that-it-can-work-like-a-queuefifo