《数据结构》实验三:栈和队列实验

《数据结构》实验三:栈和队列实验

一..实验目的

巩固栈和队列数据结构,学会运用栈和队列。

1.回顾栈和队列的逻辑结构和受限操作特点,栈和队列的物理存储结构和常见操作。

2.学习运用栈和队列的知识来解决实际问题。

3.进一步巩固程序调试方法

4.进一步巩固模板程序设计。

二.实验时间

准备时间为第5周到第6周,具体集中实验时间为6周第2次课。2个学时。

三..实验内容

1.自己选择顺序或链式存储结构,定义一个空栈类,并定义入栈、出栈、取栈元素基本操作。然后在主程序中对给定的N个数据进行验证,输出各个操作结果。


代码

<span style="font-size:14px;">Seqstack.h:
#ifndef Seqstack_H
#define Seqstack_H
const int N = 10;
class Seqstack
{
private:
int top;
int data[N];
public:
Seqstack();
~Seqstack(){};
void push(int x);  //入栈
int pop();  //出栈
int GetTop(); //取栈顶元素
int Empty();  //判空
};
#endif

函数定义文件Seqstack_func.cpp:
#include<iostream>
#include"Seqstack.h"
using namespace std;
Seqstack::Seqstack()
{
top = -1;
}
void Seqstack::push(int x)
{
if (top == N - 1) throw "overflow";
data[++top] = x;
}
int Seqstack::pop()
{
int x;
if (top == -1) throw "underflow";
x = data[top--];
return x;
}
int Seqstack::Empty()
{
if (top == -1)
{
return 1;
}
else return 0;
}
int Seqstack::GetTop()
{
if (top != -1)
return data[top];
}

主程序文件Seqstack_main.cpp:
#include<iostream>
#include<cstdlib>
#include"Seqstack.h"
using namespace std;
int main()
{
int x,y;
Seqstack S;
if (S.Empty())
{
cout << "这是空栈!" << endl;
}
else cout << "这不是空栈!" << endl;
system("pause");
cout << "分别输入两个入栈的数据:" << endl;
cout << "输入第一个数:"; cin >> x; cout << endl;
cout << "输入第二个数:"; cin >> y;
S.push(x); S.push(y);
system("pause");
cout << "栈顶元素为:" << S.GetTop() << endl;
system("pause");
cout << "执行一次出栈操作:" << endl;
S.pop();
cout << "操作后栈顶元素为:" << S.GetTop() << endl;
system("pause");
return 0;
}</span>

运行结果:



相关文章

【啊哈!算法】算法3:最常用的排序——快速排序       ...
匿名组 这里可能用到几个不同的分组构造。通过括号内围绕的正...
选择排序:从数组的起始位置处开始,把第一个元素与数组中其...
public struct Pqitem { public int priority; ...
在编写正则表达式的时候,经常会向要向正则表达式添加数量型...
来自:http://blog.csdn.net/morewindows/article/details/6...