实验4:栈和队列的基本操作实现及其应用之《链栈》
一、实验目的
1、 熟练掌栈和队列的结构特点,掌握栈和队列的顺序存储和链式存储结构和实现。
2、 学会使用栈和队列解决实际问题。
二、实验内容
建立一个链栈,实现栈的压栈和出栈操作。
#ifndef LinkStack_h
#define LinkStack_h
#include
using namespace std;
template
struct Node
{
DataType data;
Node
*next;
Node
(DataType x)
{
data = x;
next = NULL;
}
};
template
class LinkStack { public: LinkStack() { top = NULL; } ~LinkStack() {}; void Push(DataType x); DataType Pop(); DataType GetTop(); int Empty() { if (top == NULL)return 1; else return 0; } private: Node
*top; }; #endif
#include "LinkStack.h"
template
void LinkStack
::Push(DataType x)
{
Node
*s = new Node
(x);
s->next = top; top = s;
}
template
DataType LinkStack
::Pop() { if (top == NULL)throw"下溢"; DataType x = top->data; Node
*p = top; top = top->next; delete p; return x; } template
DataType LinkStack
::GetTop() { if (top == NULL) throw "空栈"; return top->data; }
#include
using namespace std;
#include "LinkStack.cpp"
void main()
{
LinkStack
s;
if (s.Empty()==0)
cout << "栈为空" << endl;
else
cout << "栈为非空" << endl;
cout << "对1和2执行入栈操作" << endl;
s.Push(1);
s.Push(2);
cout<<"栈顶元素为:"<< endl;
cout <
<< endl;
cout << "执行一次出栈操作" << endl;
s.Pop();
cout << "栈顶元素为:" << endl;
cout << s.GetTop()<< endl;
system("pause");
}