算法导论第十章10.1复习

/*
栈,队列,二叉树;
栈的基本操作:对于插入,删除操作叫做,(PUSH压入)以及(POP弹出),对于栈的话是先进后出,而队列的话是先进先出,对于队列的话具体操作有(入队列ENQUEUE)以及(出队列DEQUEUE)
*/
/***************栈操作*****************************/
#include <iostream>
using namespace std;
class stack  
{
public:
	int top;//栈顶元素位置;
	int *s;//栈采用数组进行底层操作;
	int size;
	stack(int n):top(0),size(n){
		s = new int[size+1]();
	}//n个底层为int的数组
	~stack()
	{
		delete [] s;
	}

	void print()
	{
		int i;
		for (i=1;i<=top;++i)
		{
			cout<<s[i]<<" ";
		}
		cout<<endl;
	}//打印元素
	
	bool empty()
	{
		if(top==0)
			return true;
		else 
			return false ;
	}

	void push(int num)
	{
		if(++top>size)
		{
			cerr<<"stack up flow "<<endl;
			exit(1);
		}
		s[top]=num;//第0个放弃了
	}

	int pop()
	{
		if(empty())
		{
			cerr<<"stack down flow"<<endl;
			exit(1);
		}
		return s[top--];
	}
};

/****************队列操作*************************/
struct queue
{
	int head;
	int tail;
	int size;
	int *q;
	queue(int n):size(n),head(0),tail(0){
		q=new int[size+1] ();
	}

	~queue(){
		delete [] q;
	}
	
	void enqueue(int num)
	{
		q[tail]=num;
		if(tail==size)
			tail=1;
		else
			++tail;
		
	}

	int dequeue()
	{
		int key=q[head];
		if (head=size)
			head=1;
		else
			++head;
		return key;
	}
	void print()
	{
		int i;
		if(tail>=head)
		{
			for (i=head;i<tail;++i)
			{
			cout<<q[i]<<" ";
			}
			cout<<endl;
		}else
		{
			for (i=1;i<tail;++i)
			{
				cout<<q[i]<<" ";
			}
			for (i=head;i<size;++i )
			{
				cout<<q[i]<<" ";
			}
			cout<<endl;
		}
	
	}
};

int main()
{

	stack stak(10);
	queue que(10);
	stak.push(101);
	stak.push(121);
	que.enqueue(110);
	que.enqueue(131);
	stak.print();
	que.print();
	cout<<"-----------"<<endl;
	cout<<stak.pop()<<endl;
	cout<<que.dequeue()<<endl;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值