实验三:栈和队列


实验内容

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;
	else
		cout<<"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;
	else
		return 0;
}

void main()
{
	LinkQueue Q;
	cout<<"此时队列的状态为(空队列为EMPTY,非空队列为NOT EMPTY):";
	if(Q.Empty())
		cout<<"EMPTY"<<endl;
	else
		cout<<"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;
}


执行结果为:


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值