一个用链表写的栈的模版,只写了几个最常用的功能,对象的比较没写,就是重载运算符而已。
文件“mystack.h”
#include<iostream>
using namespace std;
template<class T>
class My_stack;
template<class T>
class Node //结点类
{
private:
T data;
Node<T> *next;
public:
Node()
{
next=NULL;
}
Node(T d)
{
data=d;
next=NULL;
}
friend My_stack<T>;
};
template<class T>
class My_stack
{
private:
Node<T> *head;
public:
My_stack()
{
head=new Node<T>();
}
~My_stack()
{
clean();
delete head;
}
bool empty() const
{
return (head->next==0);
}
int size() const
{
int length=0;
Node<T> *p=head->next;
while(p)
{
length++;
p=p->next;
}
return length;
}
void push(T d) //入栈
{
Node<T> *p=new Node<T>(d);
p->next=head->next;
head->next=p;
}
T top() //返回栈顶元素
{
if(empty())
{
cout<<"stack is empty."<<endl;
exit(1);
}
Node<T> *p=head->next;
T temp=p->data;
return temp;
}
void pop() //弹出栈顶元素
{
Node<T> *p=head->next;
head->next=p->next;
delete p;
}
void clean() //清除整个栈
{
Node<T> *p=head->next;
while(p)
{
head->next=p->next;
delete p;
head->next=p;
}
cout<<"清理完成"<<endl;
}
};
下面是一个测试代码
main.cpp
#include"mystack.h"
#include<string>
using namespace std;
int main()
{
My_stack<string> s;
if(s.empty())
cout<<"stack is empty"<<endl;
//cout<<s.top()<<endl;
s.push("dan");
s.push("liu");
s.push("ai");
s.push("wo");
cout<<"Now the stack's size is: "<<s.size()<<endl;
while(!s.empty())
{
cout<<s.top()<<" ";
s.pop();
}
cout<<endl;
return 0;
}