#include <iostream>
#include <string>
using namespace std;
template<typename SElemType>
class A
{
public:
SElemType data;
A* next;
};
template<typename SElemType>
class SqStack
{
private:
A<SElemType>* top;
A<SElemType>* base;
public:
bool InitStack();
bool DestroyStack();
bool ClearStack();
bool StackEmpty();
int StackLength();
bool GetTop(SElemType* e);
bool Push(SElemType e);
bool Pop(SElemType* e);
bool StackTraverse();
};
template<typename SElemType>
bool SqStack<SElemType>::InitStack()
{/*带头结点的栈*/
base=new A<SElemType>();
if(!base)
return false;
top=base;
return true;
}
template<typename SElemType>
bool SqStack<SElemType>::DestroyStack()
{
delete base;
delete top;
return true;
}
template<typename SElemType>
bool SqStack<SElemType>::ClearStack()
{
top=base;
return true;
}
template<typename SElemType>
bool SqStack<SElemType>::StackEmpty()
{
if(top==base)
return true;
else
return false;
}
template<typename SElemType>
int SqStack<SElemType>::StackLength()
{
A<SElemType>*p=base;
int count=0;
if(top==p)
count=0;
while(p!=top)
{
p=p->next;
count++;
}
return count;
}
template<typename SElemType>
bool SqStack<SElemType>::GetTop(SElemType* e)
{
if(top!=base)
{
*e=top->data;
}
return true;
}
template<typename SElemType>
bool SqStack<SElemType>::Push(SElemType e)
{
A<SElemType>* p=new A<SElemType>();
p->data=e;
p->next=NULL;
top->next=p;
top=p;
return true;
}
template<typename SElemType>
bool SqStack<SElemType>::Pop(SElemType* e)
{
if(top==base)
return false;
*e=top->data;
A<SElemType>*p=base;
while(p->next!=top)
{
p=p->next;
}
delete top;
top=p;
top->next=NULL;
return true;
}
template<typename SElemType>
bool SqStack<SElemType>::StackTraverse()
{
if(top==base)/*空栈*/
return false;
cout<<"栈中元素为:";
A<SElemType>* p=base->next;
while(p)
{
cout<<p->data<<" ,";
p=p->next;
}
cout<<endl;
return true;
}
int main()
{
SqStack<string>S;
string s1,s2;
S.InitStack();
if(!S.StackEmpty())
cout<<"feikong"<<endl;
else
cout<<"kong"<<endl;
S.Push("zhao");
S.Push("jin");
S.Push("jia");
S.Pop(&s1);
S.StackTraverse();
S.GetTop(&s2);
cout<<S.StackLength()<<endl;
S.DestroyStack();
return 1;
}