// LinkStack.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
template<class T>
struct Node {
T data;
Node<T> *next;
};
template<class T>
class LinkStack {
public:
LinkStack();
~LinkStack();
void Push(T x);
T Pop();
T GetTop();
bool Empty();
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 = new Node<T>;
s->data = x;
s->next = top;
top = s;
}
template<class T>
T LinkStack<T>::Pop() {
T x;
Node<T> * p = top;
x = top->data;
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;
}
void main()
{
LinkStack<int>a;
if (a.Empty()) {
cout << "栈空,执行操作" << endl;
cout << "对 10进行压栈操作:" << endl;
try {
a.Push(10);
}
catch (char *wrong) {
cout << wrong;
}
cout << "读取栈顶元素:" << endl;
cout << a.GetTop() << endl;
cout << "对15栈进行压栈操作:" << endl;
try {
a.Push(15);
}
catch (char *wrong) {
cout << wrong;
}
cout << "读取栈顶元素:\n";
cout << a.GetTop() << endl;
cout << "进行出栈操作:" << endl;
a.Pop();
cout << "读取栈顶元素:" << endl;
cout << a.GetTop() << endl;
}
else {
cout << "栈不空" << endl;
}
a.~LinkStack();
system("pause");
}