封装栈与队列
栈:
#include <iostream>
using namespace std;
class Stack
{
private:
int *a; //动态数组存储元素
int size; //栈容量
int top; //栈顶元素索引
public:
//有参构造
Stack(int size):size(size),top(-1)
{
a=new int[size];
}
//析构
~Stack()
{
delete[]a;
}
//判空
bool empty()
{
return top==-1;
}
//入栈
void push_in(int const &e)
{
if(top+1==size) //二倍扩容
{
int *newa=new int[size*2];
for(int i=0;i<size;++i)
{
newa[i]=a[i];
}
delete[]a;
a=newa;
size*=2;
}
a[++top]=e;
}
//出栈
void pop()
{
if(empty())
{
cout<<"栈为空,出栈失败"<<endl;
}
else
{
--top;
}
}
//栈内元素个数
int size_1()
{
if(empty()) //栈空
{
return 0;
}
return top+1;
}
//访问栈顶元素
void at_top()
{
if(!empty())
{
cout<<"栈顶元素为:"<<a[top]<<endl;
}
else
{
cout<<"栈为空"<<endl;
}
}
//展示函数
void show()
{
cout<<"栈内元素为"<<endl;
for(int i=0;i<=top;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
};
int main()
{
Stack s(10);
s.push_in(5);
s.push_in(2);
s.push_in(0);
s.show(); //5 2 0
int count=s.size_1();
cout<<"栈内元素个数为:"<<count<<endl;
s.push_in(9);
s.show(); //5 2 0 9
s.pop();
cout<<"执行一次pop函数后"<<endl;
s.show(); //5 2 0
s.at_top(); //访问栈顶元素
s.pop();
s.pop();
s.pop(); //此时栈为空
s.pop();
return 0;
}
队列:
#include <iostream>
using namespace std;
int count=0;
class Queue
{
private:
int *a; //动态数组存储
int size; //队列容量
int front; //队头元素索引
int last; //队尾元素索引
public:
//有惨构造
Queue(int size):size(size),front(0),last(0)
{
a=new int[size];
}
//析构函数
~Queue()
{
delete []a;
}
//判空
bool empty()
{
return front==last;
}
//访问队头元素
void at_front()
{
if(empty())
{
cout<<"队列为空"<<endl;
}
else
{
cout<<"队头元素为:"<<a[front]<<endl;
}
}
//访问队尾元素
void at_last()
{
if(empty())
{
cout<<"队列为空"<<endl;
}
else
{
cout<<"队尾元素为:"<<a[(last+size-1)&size]<<endl;
}
}
//队列中元素个数
int size_1()
{
if(empty()) //栈空
{
return 0;
}
return last-front;
}
//向队尾插入元素
void push_in(int const &e)
{
if((last+1)%size==front) //二倍扩容
{
int *newa=new int[size*2];
for(int i=0;i<size;++i)
{
newa[i]=a[(front+i)&size];
}
delete []a;
a=newa;
size*=2;
front=0;
last=size/2;
}
a[last]=e;
last=(last+1)%size;
count++;
}
//删除首个元素
void pop()
{
if(empty())
{
cout<<"队列为空"<<endl;
}
else
{
front++;
front%=size;
}
}
//展示函数
void show()
{
if(empty())
{
cout<<"队列为空"<<endl;
}
else
{
cout<<"队列中元素为:"<<"";
for(int i=front;i<count;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
}
};
int main()
{
Queue q(10);
q.push_in(1);
q.push_in(3);
q.push_in(1);
q.push_in(4);
q.show(); //1 3 1 4
int haha=q.size_1();
cout<<"队列中元素个数为:"<<haha<<endl; //4
q.pop();
cout<<"执行一次pop函数后"<<endl;
q.show(); //3 1 4
q.at_front();
q.at_last(); //访问队尾元素一直显示0 抓耳挠腮仍无法解决
return 0;
}