10.1-6 说明如何用两个栈来实现一个队列,并分析有关队列操作的运行时间。
Stack A,B //A用于插入,B用于删除
ENQUEUE(Q,x)
if top[A]==n
then error "upflow"
else top[A]=top[A]+1
A[top[A]] <- x
DEQUEUE(Q,x)
if STACK-EMPTY(B)
if STACK-EMPTY(A)
error "underflow"
else
while top[A]!=0
PUSH(B,POP(A))
POP(B)
else
POP(B)
#include <iostream>
#include <string>
#include "stack.h"
using namespace std;
#define STACK_SIZE 20
#define QUEUE_SIZE 50
struct Stack{
int count;
int list[STACK_SIZE];
};
struct Queue{
int head,tail;
int list[QUEUE_SIZE];
};
void push(Stack *s,int x){
if (s->count!=STACK_SIZE){
s->list[(s->count)++]=x;
}else{
cout<<"upflow"<<endl;
}
}
int pop(Stack *s){
if (s-> count!=0){
return s->list[--(s->count)];
}else{
cout<<"underflow"<<endl;
return NULL;
}
}
bool empty_stack(Stack *s){
return s->count==0? true:false;
}
void enqueue(Stack *s1,Stack *s2,int x){
if (s1->count==STACK_SIZE){
cout<<"upflow"<<endl;
return ;
}else{
push(s1,x);
}
}
int dequeue(Stack *s1,Stack *s2){
if (empty_stack(s2)){
while (s1->count!=0){
push(s2,pop(s1));
}
return pop(s2);
}else{
return pop(s2);
}
}