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).
解决方案
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.