#ifndef linkstack_H
#define linkstack_H
template
struct Node
{
T data;
Node
*next;
};
template
class linkstack
{
public:
linkstack();
~linkstack(){};
void push(T x);
T pop();
T GetTop()
{
if (top != NULL)return top->data;
else return 0;
}
int empty()
{
if (top == NULL)return 1;
else return 0;
}
private:
Node
* top;
};
template
linkstack
::linkstack() { top = NULL; } template
void linkstack
::push(T x) { Node
*s = new Node < T >; s->data = x; s->next = top; top = s; } template
T linkstack
::pop() { T x; Node
*p = NULL; if (top == NULL) throw "underflow"; x = top->data; p = top; top = top->next; delete p; return x; } #endif #include
#include"linkstack.h" using namespace std; int main() { linkstack
L; if (L.empty()) { cout << "这是空栈!" << endl; } else cout << "这不是空栈!" << endl; cout << "对元素10和31进行入栈操作。" << endl; L.push(10); L.push(31); cout << "入栈后栈顶元素为:" << L.GetTop() << endl; cout << "进行一次出栈:" << endl; L.pop(); cout << "进行一次出栈后栈顶元素为:" << L.GetTop() << endl; system("pause"); return 0; }