10.1.6用栈实现队列
Show how to implement a queue using two stacks. Analyze the running time of the queue operations.
ENQUEUE: Θ(1).
DEQUEUE: worst O(n), amortized Θ(1).
Let the two stacks be A and B.
入列:将元素压入栈A。
出列:如果栈B为空,则将栈A的元素弹出并依次压入栈B中,然后弹出栈B的栈顶元素完成一次出列操作;若栈B不为空,直接弹出栈B的元素。
代码:
#include <iostream>
using namespace std;
struct Stack{
int data[100];
int top;
int stacksize;
};
void initStack(Stack *S)
{
S->top = -1;
S->stacksize=100;
}
bool STACK_EMPTY(Stack *S)
{
if (S->top==-1)
return true;
return false;
}
bool STACK_FULL(Stack *S)
{
if (S->top==S->stacksize-1)
return true;
return false;
}
void PUSH(Stack *S,int x)
{
S->top = S->top + 1;
S->data[S->top] = x;
}
int POP(Stack *S)
{
S->top = S->top - 1;
return S->data[S->top+1];
}
int main()
{
Stack A,B;
initStack(&A);
initStack(&B);
cout<<"1-入列,2-出列,0-结束"<<endl;
int i;
int tmp=1;
int count=0;
int x;
while(tmp){
cout<<"请选择:";
cin>>tmp;
switch(tmp){
case 0:return 0;break;
case 1:
cout<<"输入入列元素:";
cin>>x;
if (!STACK_FULL(&A))
PUSH(&A,x);
else{
cout<<"overflow"<<endl;
break;
}
count+=1;
break;
case 2:
if (STACK_EMPTY(&B)&&!STACK_EMPTY(&A)){
for(i=0;i<count;i++){
PUSH(&B,POP(&A));
}
}
if (STACK_EMPTY(&B)&&STACK_EMPTY(&A)){
cout<<"underflow"<<endl;
break;
}
cout<<"出列元素为:"<<POP(&B)<<endl;
count-=1;
break;
}
}
return 0;
}
参考文献:https://walkccc.github.io/CLRS/Chap10/10.1/