加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 05:51:36 所属栏目:安全 来源:网络整理
导读:《数据结构》实验三:???? 栈和队列实验 一..实验目的 ???? 巩固栈和队列数据结构,学会运用栈和队列。 1.回顾栈和队列的逻辑结构和受限操作特点,栈和队列的物理存储结构和常见操作。 2.学习运用栈和队列的知识来解决实际问题。 3.进一步巩固程序调试方法

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

一..实验目的

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

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

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

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

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

二..实验内容

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

三.实验报告

我选择顺序存储结构,定义一个空栈类,并定义入栈、出栈、取栈元素基本操作,然后进行验证。

#include<iostream>
using namespace std;

const int StackSize=5;
template<class DataType>
class SeqStack
{
public:
	SeqStack() {top=-1;}      //构造函数,栈的初始化
	~SeqStack() {}            //析构函数
	void Push(DataType x);    //将元素x入栈
	DataType Pop();           //将栈顶元素弹出
	DataType GetTop();        //取栈顶元素
	int Empty();              //判断栈是否为空
private:
	DataType data[StackSize];
	int top;
};

template<class DataType>
void SeqStack<DataType>::Push(DataType x)
{
	if(top==StackSize-1) throw "error!上溢!";
		top++;
	data[top]=x;
}

template<class DataType>
DataType SeqStack<DataType>::Pop()
{
	DataType x;
	if(top==-1) throw "error!下溢!";
	x=data[top--];
	return x;
}

template<class DataType>
DataType SeqStack<DataType>::GetTop()
{
	DataType x;
	if(top!=-1)
	x=data[top];
	return x;
}

template<class DataType>
int SeqStack<DataType>::Empty()
{
	if(top==-1)
		return 1;
	else return 0;
}

void main()
{
	SeqStack<int> S;
	if(S.Empty())
		cout<<"SeqStack is Empty!"<<endl;
	else
		cout<<"SeqStack is not Empty!"<<endl;
	cout<<endl;
	cout<<"对18,2,30,10和25执行入栈操作"<<endl;
	S.Push(18);
	S.Push(2);
	S.Push(30);
	S.Push(10);
	S.Push(25);
	cout<<"栈顶元素为:"<<S.GetTop()<<endl;
	cout<<endl;
	cout<<"执行一次出栈操作"<<endl;
	S.Pop();
	cout<<"栈顶元素为:"<<S.GetTop()<<endl;
}

执行结果如下:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读