手动用C++封装一个栈和队列
#include <iostream>
using namespace std;
#define MAX 8
template <typename T>
class zhan
{
private:
int top;
T arr[MAX];
public:
zhan():top(-1){}
~zhan(){}
bool pankong()
{
return this->top == -1;
}
bool panman()
{
return this->top == MAX-1;
}
int ruzhan(const T other)
{
if(panman())
throw -1;
this->top++;
arr[top] = other;
return 0;
}
int chuzhan()
{
if(pankong())
throw -1;
cout<<arr[top]<<endl;
this->top--;
return 0;
}
zhan(const zhan& other)
{
this->top = other.top;
for(int i=this->top; i>-1; i--)
{
this->arr[i] = other.arr[i];
}
}
void show()
{
cout<<"从栈顶到栈底的元素为:";
int i = 0;
for(i=this->top; i>-1; i--)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
};
int main()
{
zhan<int> s1;
for(int i=1; i<=8; i++)
{
try{ s1.ruzhan(i);
}catch(int n)
{
if(-1 == n)
cout<<"栈已经满了,入栈失败"<<endl;
}
}
s1.show();
s1.chuzhan();
s1.show();
cout<<s1.pankong()<<endl;
cout<<s1.panman()<<endl;
zhan<int> s2 = s1;
s2.show();
return 0;
}
#include <iostream>
using namespace std;
#define MAX 8
template<typename T>
class duilie
{
private:
T arr[MAX];
int front;
int tail;
public:
duilie():front(0),tail(0){}
~duilie(){}
bool pankong()
{
return front == tail;
}
bool panman()
{
return (tail+1)%MAX == front;
}
int rudui(const T other)
{
if(panman())
throw -1;
this->arr[tail] = other;
this->tail = (this->tail+1)%MAX;
return 0;
}
int chudui()
{
if(pankong())
throw -2;
cout<<arr[front]<<endl;
this->front = (this->front+1)%MAX;
return 0;
}
int show()
{
if(pankong())
throw -3;
cout<<"从队头到队尾的元素为:";
for(int i=this->front; i!=tail; i=(i+1)%MAX)
{
cout<<arr[i]<<" ";
}
cout<<endl;
return 0;
}
};
int main()
{
duilie<int> s1;
cout<<s1.pankong()<<endl;
cout<<s1.panman()<<endl;
for(int i=1; i<8; i++)
{
try {
s1.rudui(i);
} catch (int n)
{
if(-1 == n)
cout<<"队列已满,入队失败"<<endl;
}
}
s1.show();
s1.chudui();
s1.show();
cout<<s1.pankong()<<endl;
cout<<s1.panman()<<endl;
return 0;
}