数据结构 栈的链表实现法

来源:互联网 发布:印象笔记导出为知笔记 编辑:程序博客网 时间:2024/06/06 12:26
#include <iostream>
using namespace std;
template<class T>
class stackNode
{
public:
T data;
stackNode* next;
};
template<class T>
class mystack
{
private:
unsigned int stacklength;
stackNode<T> *node;
stackNode<T> *headnode;
public:
mystack();
unsigned int length();
void push(T x);
void isEmpty();
void pop();
void top();
void Traverse();
void clear();
};
template<class T>
mystack<T>::mystack()
{
node=NULL;
headnode=NULL;
stacklength=0;
};
template<class T>
void mystack<T>::push(T x)
{
node=new stackNode<T>();
node->data=x;
node->next=headnode;
headnode=node;
++stacklength;
};
template<class T>
void mystack<T>::isEmpty()
{
if( stacklength==0)
cout<<"Please input data!"<<endl;
else
cout<<"棧中一共有:"<<stacklength<<"個元素"<<endl;
};
template<class T>
void mystack<T>::pop()
{
node=headnode;
headnode=headnode->next;
delete(node);
--stacklength;
};
template<class T>
void mystack<T>::top()
{
if(headnode!=NULL)
cout<<"********************"<<endl;
cout<<"棧頂元素為: "<<headnode->data<<endl;
cout<<"********************"<<endl;

};
template<class T>
void mystack<T>::clear()
{
while(headnode!=NULL)
{
node=headnode;
headnode=headnode->next;
delete(node);
}
node=NULL;
headnode=NULL;
stacklength=0;
};
template<class T>
void mystack<T>::Traverse()
{
cout<<"-------------------------------------------"<<endl;
cout<<"棧表中的元素:";
stackNode<T>*p=headnode;
while(p!=NULL)
{
cout<<p->data<<' ';
p=p->next;
}
cout<<"\n-------------------------------------------"<<endl;
};
int main()
{
int x;
mystack<int> istack;
istack.isEmpty();
for(x=0;x<10;x++)
istack.push(x);
istack.top();
istack.Traverse();
istack.isEmpty();
istack.pop();
istack.top();
istack.Traverse();
istack.isEmpty();

istack.clear();
istack.isEmpty();




return 0;
}