微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

一..实验目的@H_404_7@

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

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

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

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

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

@H_404_7@

二..实验内容@H_404_7@

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

三.实验报告
@H_404_7@

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

@H_404_7@

#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;
}

执行结果如下:

@H_404_7@

@H_404_7@@H_404_7@

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐