// LinkStackMain.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream> //引用输入输出流
using namespace std;
template <class T>
struct Node
{
T data;
Node<T> *next; //此处<T>也可以省略
};
template <class T>
class LinkStack
{
public:
LinkStack(); //构造函数,置空链栈
~LinkStack(); //析构函数,释放链栈中各结点的存储空间
void Push(T x); //将元素x入栈
T Pop(); //将栈顶元素出栈
T GetTop(); //取栈顶元素(并不删除)
bool Empty(); //判断链栈是否为空栈
void PrintLink();
private:
Node<T> *top; //栈顶指针即链栈的头指针
};
template <class T>
LinkStack<T>::LinkStack()
{
top = NULL;
}
template <class T>
LinkStack<T>::~LinkStack()
{
while (top)
{
Node<T> *p;
p = top->next;
delete top;
top = p;
}
}
template<class T>
void LinkStack<T>::Push(T x)
{
Node<T> *s;
s = new Node<T>;
s->data = x;
s->next = top;
top = s;
}
template<class T>
T LinkStack<T>::Pop()
{
T x;
Node<T> *p;
if (top == NULL)
throw"下溢";
x = top->data;
p = top;
top = top->next;
delete p;
return x;
}
template <class T>
T LinkStack<T>::GetTop()
{
if (top != NULL)
return top->data;
}
template <class T>
bool LinkStack<T>::Empty()
{
if (top == NULL)
return 1;
else
return 0;
}
template <class T>
void LinkStack<T>::PrintLink()
{
Node<T> *p = top;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
LinkStack<int>a; //创建模板类的实例
if (a.Empty())
{
cout << "栈空,执行操作" << endl;
cout << "对 15 、10、5、0、-5栈进行压栈操作:" << endl;
try
{
a.Push(15);
a.Push(10);
a.Push(5);
a.Push(0);
a.Push(-5);
}
catch (char *wrong)
{
cout << wrong<<endl;
}
cout << "栈内元素为:";
a.PrintLink();
cout << "读取栈顶元素:\n";
cout << a.GetTop() << endl;
cout << "进行出栈操作:" << endl; //出栈操作
a.Pop();
cout << "读取栈顶元素:" << endl;
cout << a.GetTop() << endl;
}
else
{
cout << "栈不空" << endl;
}
system("pause");
return 0;
}
栈+链式
最新推荐文章于 2024-03-31 20:00:28 发布