这是去年的内容,之前放在github的一个被遗忘的reporsity里面,今天看到了就拿出来
#include<iostream>
#include<string>
using namespace std;
/*
question#1;栈的链式存储
goal:数据结构的建立、元素插入、删除等基本操作。
解释实现过程,演示实现例子以及运行结果。
*/
template <typename Type> class LinkStack;//the definition of template
template<typename Type> class LinkStackNode
{
friend class LinkStack<Type>;//the definition of friend class ,so the class LinkStack can use the private element of class LinkStack
public:
LinkStackNode(Type &e, LinkStackNode<Type> *p = NULL) :elem(e), next(p) {};
private:
Type elem;
LinkStackNode<Type>*next;//it points to the next element
};
template<typename Type>class LinkStack {
public:
LinkStack() :top(NULL) {};//the initialization of LinkStack
~LinkStack();
int IsEmpty()const { return top == NULL; }
void LinkStackClear();
int LinkStackLength()const;
Type GetTop();
void Push(Type &e);
Type Pop();
private:
LinkStackNode<Type>*top;
};
template <typename Type>//the template must be redefinited whenever it is used once
LinkStack<Type>::~LinkStack()
{
LinkStackNode<Type> *p;
while (top != NULL)
{
p = top;
top = top->next;
delete p;
}
};
//all methods are defined out of the class
template <typename Type>
void LinkStack<Type>::Push(Type &e)//Enter the LinkStack
{
LinkStackNode<Type>* p;
p = new LinkStackNode<Type>(e, top);
if (p == NULL)
{
cout << " The space distribution of LinkStackNode falls!" << endl;
return;
}
top = p;
};
template <typename Type>
Type LinkStack<Type>::Pop()
{
if (LinkStack::IsEmpty())
{
cout << "The LinkStack is empty!" << endl;
return 0;
}
LinkStackNode<Type> *p = top;
top = top->next;
Type q = p->elem;
delete p;
return q;
};
template <typename Type>
Type LinkStack<Type>::GetTop()
{
if (LinkStack::IsEmpty())
{
cout << "The LinkStack is empty!" << endl;
return 0;
}
return LinkStack::top->elem;
};
template <typename Type>
int LinkStack<Type>::LinkStackLength()const
{
LinkStackNode<Type>*p = top;
int i = 0;
while (p) { i++; p = p->next; }
return i;
};
template <typename Type>
void LinkStack<Type>::LinkStackClear()
{
LinkStackNode<Type>* p;
while (top->next != NULL)
{
p = top;
top = top->next;
delete p;
}
};
int main()
{
string a = "aspect";
LinkStack<string>temp;//Pay attention here!You can only create objections instead of new classes by this.
temp.Push(a);
cout << temp.GetTop() << endl;
cout << temp.LinkStackLength() << endl;
cout << temp.Pop() << endl;
temp.Pop()
return 0;
}