用两个栈来实现一个队列,完成队列的Push和Pop操作。队列中的元素为int类型。
算法设计
- 初始化两个栈S1,S2
*将用户输入的一串数字依次压入S1中,不断弹出S1中的数字并压入S2中 - 从S2中弹出一个数字
具体实现
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct
{
int *base;
int *top;
int stacksize;
}Stack;
//栈操作
bool InitStack(Stack &S);
bool IsEmpty(Stack S);
bool Push(Stack &S, int e);
bool Pop(Stack &S, int &e);
int main()
{
int num[64]={0};
int length=0;
int t=0;
Stack S1;
Stack S2;
InitStack(S1);
InitStack(S2);
printf("请输入数字(输入'-1'结束输入):");
for(int i=0;num[i-1]!=-1;i++)
{
scanf("%d", &num[i]);
++length;
}
length--;
for(int i=0;i<length;i++)
Push(S1, num[i]);
while(!IsEmpty(S1))
{
Pop(S1, t);
Push(S2, t);
}
while(!IsEmpty(S2))
{
Pop(S2, t);
printf("%d ",t);
}
}
bool InitStack(Stack &S)
{
S.base = (int*)malloc(MAXSIZE*sizeof(int));
if(!S.base) return 0;
S.top = S.base;
S.stacksize = MAXSIZE;
return 1;
}
bool IsEmpty(Stack S)
{
if(S.top == S.base) return 1;
return 0;
}
bool Push(Stack &S, int e)
{
if(S.top-S.base == S.stacksize) return 0;
*S.top = e;
S.top++;
return 1;
}
bool Pop(Stack &S, int &e)
{
if(S.top == S.base) return 0;
S.top--;
e = *S.top;
return 1;
}