The array realizes the double-ended queue when the difference between the overflow and the underflow is observed.
Implementing a queue with two stacks is equivalent to putting two stacks together (back-to-back), one stack for the queue, and one stack for the queue. The operation time of this queue is mostly constant time, except that the stack of the column is empty, it needs to transfer the stack in the past and then dequeue. The back () operation is similar to the pop () operation.
and two queue implementation stack, the queue to act as the stack and the role of the stack, and when will change the role, is the pop () operation. The Pop () operation first queues all the elements in a queue and joins another empty queue, then dequeue (the second queue).
The implementation code is C
#include <stdio.h>#include<stdlib.h>#defineMax 100//double-ended queue implementation Ctypedefstruct{ intHead; inttail; intA[max];} Deque;voidInit_deque (Deque *d) {D->head =-1; D->tail =0;}BOOLEmpty (Deque *d) { returnD->head = =-1;}voidPush_back (Deque *d,intkey) { if(D->head = = d->tail) {fprintf (stderr,"Deque Overflow"); Exit (1); } if(D->head = =-1) d->head = d->tail; D->a[d->tail] =key; D->tail = (D->tail +1) %Max;}intPop_back (Deque *d) { if(D->head = =-1) {fprintf (stderr,"Deque underflow"); Exit (1); } d->tail = (D->tail-1+max)%Max; if(D->head = = d->tail) d->head =-1; returnD->a[d->tail];}voidPush_front (Deque *d,intkey) { if(D->head = = d->tail) {fprintf (stderr,"Deque Overflow"); Exit (1); } if(D->head = =-1) d->head = d->tail; D->head = (D->head-1+ Max)%Max; D->head =key;}intPop_front (Deque *d) { if(D->head = =-1) {fprintf (stderr,"Deque underflow"); Exit (1); } inttemp = d->a[d->Head]; D->head = (D->head +1) %Max; if(D->head = = d->tail) d->head =-1; returntemp;}//two stacks to implement a queuetypedefstruct{Deque inqueue; Deque dequeue;} Like_queue;voidPush (Like_queue *LQ,intkey) {Push_back (&lq->Inqueue, key);}intPop (Like_queue *LQ) { if(Empty (&lq->dequeue)) { while(! Empty (&lq->inqueue)) { inttemp = Pop_back (&lq->inqueue); Push_back (&lq->dequeue, temp); } } returnPop_back (&lq->dequeue);}
Introduction to two-terminal queue C implementation code algorithm 10.1-5 10.1-6 10.1-7