数据结构与算法之—两个栈实现一个队列

#include<iostream>
using namespace std;

class my_stack
{
	public:
		my_stack(int n = 0);
		virtual ~my_stack();
		bool empty(void)const;
		bool full(void)const;
		bool push(const int& new_data);
		bool pop(void);
		bool get_top(int& top)const;

	private:
		int *a;
		int max_size;
		int size;
};

my_stack::my_stack(int n)
{
	size = 0;
	if(n <= 0)
	{
		a = NULL;
		max_size = 0;
	}
	else
	{
		a = new int[n];
		if(a == NULL)
		{
			max_size = 0;
		}
		else
		{
			max_size = n;
		}
	}
}

my_stack::~my_stack()
{
	delete []a;
}

bool my_stack::empty(void)const
{
	return size == 0 ? true : false;
}

bool my_stack::full(void)const
{
	return size == max_size ? true : false;
}

bool my_stack::push(const int& new_data)
{
	if(!full())
	{
		a[size++] = new_data;
		
		return true;
	}
	else
	{
		return false;
	}
}

bool my_stack::pop(void)
{
	if(empty())
	{
		return false;
	}
	else
	{
		size--;
		return true;
	}
}

bool my_stack::get_top(int &top)const
{
	
	if(empty())
	{
		return false;
	}
	else
	{
		top = a[size-1];
		return true;
	}
}

class stack_queue
{
	public:
		stack_queue(int n);
		virtual ~stack_queue();
		bool full(void)const;
		bool empty(void)const;
		bool push(const int& new_data);
		bool pop(int &front);

	private:
		my_stack *s1;
		my_stack *s2;
		int max_size;
		int size;

};

stack_queue::stack_queue(int n)
{
	s1 = new my_stack(n);
	s2 = new my_stack(n);
	size = 0;
	max_size = 2*n;
}

stack_queue::~stack_queue()
{
	delete s1;
	delete s2;
}

bool stack_queue::empty(void)const
{
	return s1->empty() && s2->empty() ? true : false;
}

bool stack_queue::full(void)const
{
	return s1->full() ? true : false;
}

bool stack_queue::push(const int& new_data)
{
	if(full())
	{
		return false;
	}
	
	if(!s1->full())
	{
		s1->push(new_data);
	}
	
	if(s1->full() && s2->empty())
	{
		while(!s2->full() && !s1->empty())
		{
			int top = -1;
			if(s1->get_top(top))
			{
				s2->push(top);
				s1->pop();
			}
		}
	}
		

	return true;
}

bool stack_queue::pop(int& front)
{
	if(empty())
	{
		return false;
	}

	if(!s2->empty())
	{
		int top = -1;
		s2->get_top(top);
		front = top;
		s2->pop();
	}
	else
	{
		int top = -1;
		while(!s1->empty())
		{
			s1->get_top(top);
			front = top;
			s2->push(top);
			s1->pop();
		}
		s2->get_top(top);
		s2->pop();
	}

	return true;


}





int main()
{
	stack_queue q(5);

	//入队
	for(int i = 0; i < 10; i++)
	{
		q.push(i);
	}

	//出队
	for(i = 0; i < 10; i++)
	{
		int  top = -1;
		if(q.pop(top))
		{
			cout<<top<<endl;
		}
	
	}

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值