准备考研中,刷了一遍书,重看第二遍时有个题目是:两个栈st1,st2来模拟队列,采用顺序栈,栈中元素最多为maxSize。要求:写出入队,出队,判断队列是否为空。
这里唯一要注意的是,maxSize >= (入队列数据的长度)/2。
然后用st1作为入队的栈,st2作为出队的栈。
#include<iostream>
#include<stdlib.h>
#include<time.h>
#define maxSize 10
using namespace std;
typedef struct
{
int data[maxSize];
int top;
}SqStack;
//栈的一些基本操作
void initStack(SqStack &st)
{
st.top = -1;
}
int isEmpty(SqStack st)
{
if(st.top == -1)
return 1;
else
return 0;
}
int isTop(SqStack st)
{
if(st.top == maxSize-1)
return 1;
else
return 0;
}
int getTop(SqStack st, int &x)
{
if(st.top == -1)
return 0;
x = st.data[st.top];
return 1;
}
int Push(SqStack &st, int x)
{
if(st.top == maxSize-1)
return 0;
++(st.top);
st.data[st.top] = x;
return 1;
}
int Pop(SqStack &st, int &x)
{
if(st.top == -1)
return 0;
x = st.data[st.top];
--(st.top);
return 1;
}
//模拟进队列
int enqueue(SqStack &st1, SqStack &st2, int x)
{
int data;
//如果st1队列没有满则直接进栈,否则判断st2,如果为空,则将st1中
//的元素出栈压入st2,在将原来要进栈的元素x压入st1
if(!isTop(st1))
{
Push(st1, x);
return 1;
}else{
if(!isEmpty(st2))
return 0;
else
{
while(!isEmpty(st1))
{
Pop(st1, data);
Push(st2, data);
}
Push(st1, x);
return 1;
}
}
}
//模拟出队列
int dequeue(SqStack &st1, SqStack &st2, int &x)
{
int data;
if(!isEmpty(st2))
{
Pop(st2, x);
return 1;
}else{
if(isEmpty(st1))
return 0;
else
{
while(!isEmpty(st1))
{
Pop(st1, data);
Push(st2, data);
}
Pop(st2, x);
return 1;
}
}
}
//判断队列是否为空
int queue_isEmpty(SqStack st1, SqStack st2)
{
if(isEmpty(st1) && isEmpty(st2))
return 1;
else
return 0;
}
//生成随即数组
void randArr(int *arr, int n)
{
srand(time(0));
int i=0;
for(;i<n;i++)
arr[i] = rand()%100+1;
}
//打印数组
void showArr(int *arr, int n)
{
int i=0;
for(;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
int main()
{
int n = 20;
int *arr = (int *)malloc(n*sizeof(int));
randArr(arr, n);
showArr(arr, n);
int i, data;
SqStack st1, st2;
initStack(st1);
initStack(st2);
for(i=0; i<n; ++i)
enqueue(st1, st2, arr[i]);
for(i=0; i<n; ++i)
{
dequeue(st1, st2, data);
cout<<data<<" ";
}
return 0;
}
这是正常的maxSize=10, 数据长度n=20
这是正常的maxSize=9时, 数据长度n=20