#include <iostream>
using namespace std;
typedef int Status;
const int OK = 1;
const int ERROR = 0;
template <class T>
struct Node
{
T data;
Node<T> *next;
};
template <class T>
class LinkStack
{
public:
LinkStack();
~LinkStack();
Status Push(T e);
Status Pop(T &e);
Status GetTop(T &e);
int StackLength();
Status IsEmpty();
void DispStack();
private:
Node<T> *top;
};
template <class T>
LinkStack<T>::LinkStack()
{
top = new Node<T>;
top->next = nullptr;
}
template <class T>
LinkStack<T>::~LinkStack()
{
Node<T> *p = top;
while(p != NULL)
{
p = p->next;
delete top;
top = p;
}
}
template <class T>
Status LinkStack<T>::Push(T e)
{
Node<T> *p = new Node<T>;
if(p == NULL)
{
return ERROR;
}
p->data = e;
p->next = top->next;
top->next = p;
return OK;
}
template <class T>
Status LinkStack<T>::Pop(T &e)
{
Node<T> *p;
if(top->next == NULL)
{
return ERROR;
}
p = top->next;
e = p->data;
top->next = p->next;
delete p;
return OK;
}
template <class T>
void LinkStack<T>::DispStack()
{
Node<T> *p = NULL;
if(top->next == NULL)
{
return;
}
p = top->next;
while(p != NULL)
{
cout<< p->data << " ";
p = p->next;
}
cout<< endl;
}
template <class T>
Status LinkStack<T>::GetTop(T &e)
{
if(top->next == NULL)
{
return ERROR;
}
e = top->next->data;
return OK;
}
template <class T>
int LinkStack<T>::StackLength()
{
Node<T> *p = top->next;
int cnt = 0;
while(p != NULL)
{
cnt++;
p = p->next;
}
return cnt;
}
template <class T>
Status LinkStack<T>::IsEmpty()
{
return (top->next == NULL)? OK:ERROR;
}
int main()
{
LinkStack<int> stack1;
for(int i=0; i<10; i++)
{
stack1.Push(i);
}
stack1.DispStack();
int temp = 0;
for(int i=0; i<10; i++)
{
stack1.Pop(temp);
cout<< temp << " ";
}
cout<< endl;
cout << "**************" << endl;
stack1.DispStack();
cout<< stack1.IsEmpty()<<endl;
cout << "***************"<<endl;
temp = 4;
stack1.GetTop(temp);
cout << temp <<endl;
for(int i=0; i<10; i++)
{
stack1.Push(i);
}
stack1.DispStack();
stack1.GetTop(temp);
cout<< temp << endl;
cout << "链栈长为:" << stack1.StackLength()<<endl;
stack1.Pop(temp);
cout<<temp <<endl;
cout << "链栈长为:" << stack1.StackLength()<<endl;
cout<< stack1.IsEmpty()<<endl;
return 0;
}
