题目基本描述:给定一个数组,大小给定,用n表示,让你设计个程序,用该数组实现队列的基本操作
基本思路:定义一个变量star,代表如果从队列中跳出一个数,应该跳出数组star位置上的数,定义一个变量end,代表如果往队列里面放入一个数,放入到数组中end位置,再定义一个变量size1代表队列当前的大小。
进行push操作:如果size1的值大于数组的大小时,说明队列已经满了,给用户报错。否则(可以往队列中加入一个数),加入到数组end位置,然后end加1,为加入下一个数做准备,如果end大于数组的大小,让end变为0,继续进行push操作。
进行pop操作:如果size1等于0,说明队列中没有数了,给用户报错。否则(队列中有数),输出star位置上的数,star加1,为输出下一个数做准备,如果star大于数组的大小,让star变为0,继续进行pop操作。
代码如下:
#include<bits/stdc++.h>
using namespace std;
int a[3];
string b;
int star=0;//表示如果跳出一个数,就跳出star上的数
int size1=0;//当前数组的大小
int end=0;//表示加入一个数,加入到数组的end位置
void push(int n)
{
if(size1==3)//当当前的队列的大小已经到达了3,可是还要往里加数,显然加不上了,报错
{
cout<<"error"<<endl;
return ;
}
else
{ //如果能进这里,说明可以往这个数组中加入数字
if(end!=3)
{
a[end++]=n;
size1++;
}
else//当应该加入的数的位置大于数组的范围时,把这个位置给返回到数组开头
{
end=0;
a[end++]=n;
size1++;
}
}
}
void pop()
{
if(size1==0)
{
cout<<"error"<<endl;
return ;
}
else
{ //同push
if(star!=3)
{
cout<<a[star++]<<endl;
size1--;
}
else
{
star=0;
cout<<a[star++]<<endl;
size1--;
}
}
}
int main()
{
while (cin>>b)
{
if(b=="push")
{
int number;
cin>>number;
push(number);
}
if(b=="pop")
pop();
}
}
其实,就相当于star在追着end(但是不可能追上,最多star等于end,这时队列中没有数字,即size1等于0),如果end到头了(即到了数组大小的位置了),就让end回来,star也是如此