类 栈
#include <iostream>
using namespace std;
class Sta{
private:
int *data;
int top;
public:
Sta():data(new int(128)){
top=-1;
cout<<"stack::无参构造:"<<endl;
}
~Sta(){
delete data;
cout<<"stack::析构函数:"<<this<<endl;
}
Sta(const Sta &other):data(new int (*other.data)),top(other.top){
cout<<"拷贝构造函数"<<endl;
}
int empty(){
return top==-1;
}
int full(){
return top==127;
}
int statop(){
return data[top];
}
int pop(){
if(empty()!=1){
int a=data[top];
cout<<"出栈成功:"<<a<<endl;
top--;
return 1;
}
return -1;
}
int push(int a){
if(full()!=1){
top++;
data[top]=a;
cout<<"入栈成功:"<<endl;
return 1;
}
return -1;
}
int size(){
cout<<"size:"<<top<<endl;
return top;
}
int clean(){
top=0;
return 0;
}
};
int main()
{
Sta sta;
sta.push(4);
sta.push(5);
sta.push(1);
sta.push(5);
sta.push(8);
cout<<sta.statop()<<endl;
Sta sta1=sta;
return 0;
}
类 队列
#include <iostream>
using namespace std;
class Sta{
private:
int *data;
int head;
int tail;
public:
Sta():data(new int(10)){
head=0;
tail=1;
cout<<"stack::无参构造:"<<endl;
}
~Sta(){
delete data;
cout<<"stack::析构函数:"<<this<<endl;
}
Sta(const Sta &other):data(new int (*other.data)),head(other.head),tail(other.tail){
cout<<"拷贝构造函数"<<endl;
}
int empty(){
return head==tail;
}
int full(){
return (tail+1+10)%10==head;
}
int pop(){
if(empty()!=1){
int a=data[head];
cout<<"出队列成功:"<<a<<endl;
head++;
return 1;
}
return -1;
}
int push(int a){
if(full()!=1){
data[tail]=a;
tail++;
cout<<"入队列成功:"<<endl;
return 1;
}
return -1;
}
int size(){
int len=(tail-head+10)%10;
cout<<"size:"<<len<<endl;
return len;
}
int clean(){
head=tail=0;
return 0;
}
};
int main()
{
Sta sta;
sta.push(4);
sta.push(5);
sta.push(1);
sta.push(5);
sta.push(8);
cout<<sta.pop()<<endl;;
Sta sta1=sta;
return 0;
}