类中包含一个指针指向栈顶的元素,定义一个结构体,包括值和一个指向他上一个元素的指针。
#include <iostream>
#define NULL 0
using namespace std;
class MyStack
{
private:
struct node
{
int s;
node *link;
};
node *top;
public:
MyStack()
{
top=NULL;
}
~MyStack()
{
node *temp;
while(top)
{
temp=top;
top=temp->link;
delete temp;
}
}
bool Add(int a);
bool Delete(int &a);
inline bool StackEmpty()
{
if(top) return false;
else return true;
}
};
bool MyStack::Add(int a)
{
node *temp = new node;
if(temp)
{
temp->link=top;
temp->s=a;
top=temp;
return true;
}
else
{
cout << "failed" << endl;
return false;
}
}
bool MyStack::Delete(int &a)
{
if(!StackEmpty())
{
node *temp;
temp=top;
a=temp->s;
top=temp->link;
delete temp;
return true;
}
else
{
cout << "the stack is empty" << endl;
return false;
}
}
int main()
{
int a;
MyStack s;
s.Add(3);
s.Add(2);
s.Add(1);
for(int i=0;i<3;i++)
{
s.Delete(a);
cout << a << endl;
}
return 0;
}