实验三:栈和队列
来源:互联网 发布:airbnb 代订陷阱 淘宝 编辑:程序博客网 时间:2024/06/10 02:37
实验内容1.自己选择顺序或链式存储结构,定义一个空栈类,并定义入栈、出栈、取栈元素基本操作。然后在主程序中对给定的N个数据进行验证,输出各个操作结果。
2.自己选择顺序或链式存储结构,定义一个空栈队列,并定义入栈、出栈、取栈元素基本操作。然后在主程序中对给定的N个数据进行验证,输出各个操作结果。
1、栈——顺序栈的实现:
#include<iostream>#include<iomanip>using namespace std;const int StackSize = 10;class SeqStack{public:SeqStack();~SeqStack(){};void Push(int x);int Pop();int GetTop();int Empty();private:int data[StackSize];int top;};SeqStack::SeqStack(){ top = -1;}void SeqStack::Push(int x){if(top == StackSize - 1)throw"上溢";top++;data[top] = x;}int SeqStack::Pop(){int x;if(top == -1)throw"下溢";x = data[top--];return x;}int SeqStack::GetTop(){if(top != -1)return data[top];}int SeqStack::Empty(){if(top == -1)return 1;else return 0;}void main(){ SeqStack S;cout<<"此时栈的状态为(空栈为EMPTY;非空栈为NOT EMPTY):";if(S.Empty())cout<<"EMPTY"<<endl;elsecout<<"NOT EMPTY"<<endl;cout<<"进行插入数据1和2的操作"<<endl;S.Push(1);S.Push(2);cout<<"此时栈顶元素为:"<<endl;cout<<S.GetTop()<<endl;cout<<"进行出栈一个数据的操作"<<endl;S.Pop();cout<<"此时栈顶元素为:"<<endl;cout<<S.GetTop()<<endl;}
执行结果:
2、队列——链队列的实现:
#include<iostream>using namespace std;struct Node{int data;Node *next;};class LinkQueue{public:LinkQueue();~LinkQueue();void EnQueue(int x);int DeQueue();int GetQueue();int Empty();private:Node *front,*rear;};LinkQueue::LinkQueue(){Node *s = NULL;s = new Node;s -> next = NULL;front = rear = s;}LinkQueue::~LinkQueue(){Node *p = NULL;while(front != NULL){p = front -> next;delete front;front = p;}}void LinkQueue::EnQueue(int x){Node *s = NULL;s = new Node;s -> data = x;s -> next = NULL;rear -> next = s;rear = s;}int LinkQueue::DeQueue(){Node *p = NULL;int x;if(rear == front)throw"下溢";p = front -> next;x = p -> data;front -> next = p -> next;if(p -> next == NULL)rear = front;delete p;return x;}int LinkQueue::GetQueue(){if(front != rear)return front -> next -> data;}int LinkQueue::Empty(){if(front == rear)return 1;elsereturn 0;}void main(){LinkQueue Q;cout<<"此时队列的状态为(空队列为EMPTY,非空队列为NOT EMPTY):";if(Q.Empty())cout<<"EMPTY"<<endl;elsecout<<"NOT EMPTY"<<endl;cout<<"执行插入数据1和2的操作"<<endl;try{Q.EnQueue(1);Q.EnQueue(2);}catch(char *wrong){cout<<wrong<<endl;}cout<<"此时队列的对头元素为:"<<endl;cout<<Q.GetQueue()<<endl;cout<<"执行一次出队操作"<<endl;try{Q.DeQueue();}catch(char * wrong){cout<<wrong<<endl;}cout<<"此时队列的队头元素为:"<<endl;cout<<Q.GetQueue()<<endl;}
执行结果为:
0 0
- 实验三 栈和队列
- 实验三:栈和队列
- 实验三栈和队列
- 实验三 栈和队列
- 实验三 栈和队列
- 【实验三】栈和队列
- 实验三 栈和队列
- 实验三-栈和队列
- 实验三: 栈和队列实验
- 《数据结构》实验三: 栈和队列实验
- 《数据结构》实验三: 栈和队列实验
- 《数据结构》实验三:栈和队列实验
- 《数据结构》实验三: 栈和队列实验
- 《数据结构》实验三: 栈和队列实验
- 《数据结构》实验三:栈和队列实验
- 数据结构:实验三 栈和队列实验
- 《数据结构》实验三: 栈和队列实验
- 实验三:栈和队列实验
- KMP算法深入解析
- Dreamweaver代码
- 几种常见的I/O模型及其区别
- apriori算法简单实现
- 数据结构——最大值最小化 (划分子序列)
- 实验三:栈和队列
- spring3,springMVC,Hibernate4整合开发
- Pascal Triangle
- uva 10534(最长上升子序列O(nlogn))
- MySQL获取刚插入的数据
- django 中Model一些笔记--收藏
- Sql Server2005数据库在还原时出现如下错误信息:
- struts2 action重定向
- Eight Docker Development Patterns