1
错误
2
m
3
#include <bits/stdc++.h>
using namespace std;
const int M = 100;
int a[100],l=0,cnt=0;
bool push(int x){
if(cnt>=M)return false;
else a[(l+cnt++)%M]=x;
return true;
}
int pop(){
if(cnt<= 0)return INT32_MIN;
else return a[l+(--cnt)];
}
void show(){
cout<<"队列为:";
for(int i=0;i<cnt;++i)
cout<<a[(l+i)%M]<<' ';
cout<<endl;
}
int main(){
int op, p;
while(cin>>op && op!=-1){
cout<<"请选择您所需的操作:\n1.入队\n2.出队\n-1.退出"<<endl;
int x;
switch (op){
case 1:
cin>>x;
push(x);
show();
break;
case 2:
p=pop();
if(p==INT32_MIN)cout<<"队列为空"<<endl;
else cout<<"出队的元素为:"<<pop()<<endl;
break;
}
}
return 0;
}
4
#include <bits/stdc++.h>
using namespace std;
class mydeque{
private:
int l,r,cnt;
int *p;
public:
static int maxn;
mydeque():l(0),r(1),cnt(0){p = new int[maxn];};
~mydeque(){ delete p;}
bool push(int x);
int pop();
bool inject(int x);
int eject();
bool is_full(){return cnt==maxn;};
bool is_empty(){return cnt==0;};
void show();
};
int mydeque::maxn = 100;
bool mydeque::push(int x){
if(is_full()) return false;
else {
int maxnn=mydeque::maxn;
p[l] = x;
l=(l-1+maxnn)%maxnn;
cnt++;
}
}
int mydeque::pop(){
if(is_empty()) return INT32_MIN;
else {
l=(l+1)%mydeque::maxn;
cnt--;
return p[l];
}
}
bool mydeque::inject(int x){
if(is_full()) return false;
else {
p[r]=x;
r=(r+1)%mydeque::maxn;
cnt++;
}
}
int mydeque::eject(){
if(is_empty()) return INT32_MIN;
else {
int maxnn=mydeque::maxn;
r=(r-1+maxnn)%maxnn;
cnt--;
return p[r];
}
}
void mydeque::show(){
cout<<"当前队列中的元素: ";
for(int i=1;i<=cnt;++i)
cout<<p[(l+i)%mydeque::maxn]<<" ";
cout<<endl;
}
int main(){
mydeque dq;
cout<<"请输入操作:\n1.队头入队\t2.队头出队\t3.队尾入队\t4.队尾出队\t-1.结束\n";
int op;
while(cin>>op && op!=-1){
int x, tmp;
switch(op){
case 1:
cin>>x;
dq.push(x);
dq.show();
break;
case 2:
tmp=dq.pop();
if(tmp==INT32_MIN) cout<<"队列为空\n";
else cout<<"出队元素为"<<tmp<<endl;
break;
case 3:
cin>>x;
dq.inject(x);
dq.show();
break;
case 4:
tmp=dq.eject();
if(tmp==INT32_MIN) cout<<"队列为空\n";
else cout<<"出队元素为"<<tmp<<endl;
break;
}
}
}