每次入栈操作相当于在链表的头部插入元素
#include<iostream>
#define ElemType int
struct Stacklist
{
Stacklist* next;
ElemType data;
};
class Stack
{
private:
Stacklist* top ;
public:
Stack() ;
~Stack() ;
void InitStack();
bool pop(ElemType &e);
bool push(ElemType e);
};
Stack::Stack()
{
top = new Stacklist[1];
top->next = NULL ;
}
Stack::~Stack()
{
delete []top ;
}
bool Stack::pop(ElemType &e)
{
if(top->next == NULL)
{
return false ;
}
Stacklist* firstNode ;
firstNode = top->next ;
e = firstNode->data ;
top->next = firstNode->next ;
delete []firstNode ;
return true ;
}
bool Stack::push(ElemType e)
{
Stacklist* Node ;
Node = new Stacklist[1] ;
Node->data = e ;
Node->next = top->next ;
top->next = Node ;
return true ;
}
int main()
{
Stack st ;
int a = 1;
for(int i = 0 ;i<10;i++)
{
st.push(i) ;
}
for(int i=0;i<10;i++ )
{
st.pop(a);
cout<<a<<" " ;
}
cout<<endl;
system("pause");
}