1、自己确定结点的具体数据类型和问题规模:
分别建立一个顺序栈和链栈,实现栈的压栈和出栈操作。
#include<iostream>
using namespace std;
template<class DataType>
struct Node
{
DataType data;
Node<DataType>*next;
};
template<class DataType>
class LinkStack
{
private:
Node<DataType>*top, *s, *p;
public:
LinkStack() { top = NULL; }
~LinkStack(){}
void Push(DataType x);
DataType Pop();
DataType GetTop() { if (top != NULL)return top->data; }
int Empty()
{
if (top == NULL) return 1;
else return 0;
}
};
template<class DataType>
void LinkStack<DataType>::Push(DataType x)
{
s = new Node<DataType>;
s->data = x;
s->next = top; top = s;
}
template<class DataType>
DataType LinkStack<DataType>::Pop()
{
if (top == NULL) throw"下溢";
DataType x = top->data; p = top;
top = top->next;
delete p;
return x;
}
int main()
{
LinkStack<int>stu;
stu.Push(11);
stu.Push(22);
stu.Push(33);
cout<<stu.GetTop() << endl;
cout << stu.Empty() << endl;
cout << stu.Pop()<<endl;
cout << stu.Pop() << endl;
cout << stu.Pop() << endl;
cout << stu.Empty() << endl;
}