顺序栈:
#include <iostream>
#define MAXSIZE 20
using namespace std;
class stack
{
private:
int *ptr;
int top;
public:
stack(int size,int t):ptr(new int[size]),top(t){}
//析构函数
~stack()
{
delete []ptr;
}
//判空
bool empty();
//判满
bool full();
//入栈
int push(int num);
//出栈
int pop();
//遍历
void output();
//取栈顶元素
int &gettop();
};
int main()
{
stack sp(MAXSIZE,-1);//创建并初始化类对象
int num = 0;
for(int i=0; i<5; i++)//循环入栈
{
cout<<"请入栈:";
cin>>num;
while(getchar()!='\n');
sp.push(num);
}
cout<<"当前栈内元素:";
sp.output();
while(1)//循环出栈
{
cout<<"确定要出栈吗y/n?"<<endl;
if(int y = getchar()=='y')
sp.pop();
else if(y=='n')
break;
while(getchar()!='\n');//吸收回车
sp.output();
}
cout<<"出栈结束,当前站内元素是:";
sp.output();
cout<<"当前栈顶元素是: "<<sp.gettop()<<endl;
return 0;
}
bool stack::empty()
{
return top==-1?true:false;
}
bool stack::full()
{
return top==MAXSIZE-1?true:false;
}
int stack::push(int num)
{
if(this->full())
{
cout<<"栈满,无法入栈\n"<<endl;
return -1;
}
*(ptr+top+1)=num;
top++;
return 0;
}
int stack::pop()
{
if(this->empty())
{
cout<<"栈空,无法出栈"<<endl;
return -1;
}
top--;
return 0;
}
void stack::output()
{
if(this->empty())
{
cout<<"栈空,无法遍历"<<endl;
return ;
}
for(int i=0;i<=top;i++)
{
cout<<*(ptr+i);
}
cout<<endl;
}
int &stack::gettop()
{
if(this->empty())
{
cout<<"栈空,无法取栈顶"<<endl;
}
int &ref = *(ptr+top);
return ref;
}
循环队列
#include <iostream>
#define MAXSIZE 10
using namespace std;
class LoopList
{
int *ptr;
int start;
int end;
public:
//构造函数
LoopList(int size,int start,int end):ptr(new int[size]),start(start),end(end){}
//析构函数
~LoopList()
{
delete []ptr;
}
//判空
bool empty();
//判满
bool full();
//入队
int pushqueue(int num);
//出队
int popqueue();
//计算队列个数
int sizeofqueue();
//遍历队列
void output();
};
int main()
{
LoopList Q(MAXSIZE,0,0);
//循环入队
for(int i=0;i<5;i++)
{
int num;
cout<<"请入队:";
cin>>num;
while(getchar()!='\n');
Q.pushqueue(num);
}
//打印队列
cout<<"入队结束,当前队列是:";
Q.output();
//循环出队
while(1)
{
cout<<"是否要出队y/n?";
if(getchar()=='y')
Q.popqueue();
else
break;
while(getchar()!='\n');
cout<<"当前队列元素的个数为:"<<Q.sizeofqueue()<<"分别是:";
Q.output();
}
return 0;
}
bool LoopList::empty()
{
return start==end?true:false;
}
bool LoopList::full()
{
return start == (end+1)%MAXSIZE?true:false;
}
int LoopList::popqueue()
{
if(this->empty())
{
cout<<"栈空,无法出队"<<endl;
return -1;
}
start = (start+1)%MAXSIZE;
return 0;
}
int LoopList::sizeofqueue()
{
return (MAXSIZE-start+end)%MAXSIZE;
}
void LoopList::output()
{
if(this->empty())
{
cout<<"队列空,无法遍历"<<endl;
return ;
}
for(int i=start;i!=end;i=(i+1)%MAXSIZE)
{
cout<<*(ptr+i)<<" ";
}
cout<<endl;
}
int LoopList::pushqueue(int num)
{
if(this->full())
{
cout<<"队列满,无法入队"<<endl;
return -1;
}
*(ptr+end) = num;
end = (end+1)%MAXSIZE;
return 0;
}
思维导图在这里
https://www.mubu.com/doc/7FxL_beFGyz
https://www.mubu.com/doc/1eLZGsakHOz