实验三——顺序栈

来源:互联网 发布:php程序员发展前景 编辑:程序博客网 时间:2024/06/05 18:06

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

一..实验目的

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

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

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

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

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

二.实验时间

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

三..实验内容

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

源代码:

头文件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;
}


0 0