通过栈来实现队列

思路:这一类问题主要是考虑你的思路,算法本身应该并没有什么实际的应用(鄙人见少视浅,如果有具体的应用的地方,欢迎各位指出),其实这类问题之前也遇到过,如某概率产生器以p和1-p产生A,B,怎么构造出0.5的概率产生器。p和1-p怎么才能产生相等的关系呢,其实,我们知道p*(1-p) = (1-p)*p 所以我们简单的利用这个原理,就可以实现0.5的概率产生器。也就是产生AB和BA的概率总是相等的。我们只需要查看两次连续的输出值,将AA和BB丢弃,那么剩下的AB和BA的概率都是0.5.再如我们的字符串移位操作,AB要转为BA 怎么实现,(A'B')'  即将A,B分别转置后再整体转置,就可得到BA。
 
这里的思路也是一样:栈的性质正好与队列想反,好在我们有这样的概念,双重否定不就是肯定吗?所以我们就用两个栈来实现一个队列不就行啦……
 
/*
 *栈的特点是后进先出,队列的特点是先进先出。所以,用两个栈s1和s2模拟一个队列时,s1作输入栈,
 *逐个元素压栈,以此模拟队列元素的入队。当需要出队时,将栈s1退栈并逐个压入栈s2中,s1中最先
 *入栈的元素,在s2中处于栈顶。s2退栈,相当于队列的出队,实现了先进先出。显然,只有栈s2为空
 *且s1也为空,才算是队列空。算法中假定栈s1和栈s2容量相同。出队从栈s2出,当s2为空时,若s1
 *不空,则将s1倒入s2再出…
 */

#include "stdafx.h"

#include<iostream.h>

const int N = 20;

class Stack
{
 public:
  Stack();
  bool Push(int);
  bool Pop(int&);
  bool StackEmpty();
  bool StackFull();

 private:
  int num[N];
  int top;
};

Stack::Stack()
{
 top = 0;
}

bool Stack::StackEmpty()
{
 return top == 0;
}

bool Stack::StackFull()
{
 return top == N-1;
}
bool Stack::Push(int e)
{
  if(StackFull())
  {
 cout<<"Error:Stack Full!"<<endl;
 return false;
  }
  num[top++] = e;  
  return true;
}

bool Stack::Pop(int& e)
{
 if(StackEmpty())
 {
  cout<<"Error:Stack Empty!"<<endl;
  return false;
 }
 e = num[--top];
 return true;
}

class Queue
{
 public:
  Queue(){};
   bool EnQueue(int);
  bool DelQueue(int&);
  bool QueueEmpty();
  bool QueueFull();
    
 private:
  Stack s1,s2;
};

bool Queue::QueueEmpty()
{
 if(s1.StackEmpty() && s2.StackEmpty())
  return true;
 return false;
}

bool Queue::QueueFull()
{
 if(s1.StackFull())
  return true;

 return false;
}

bool Queue::EnQueue(int e)
{
 if(QueueFull())
 {
  cout<<"Error:Queue Full!"<<endl;
  return false;
 }

 s1.Push(e);
 return true;
}

bool Queue::DelQueue(int& e)
{
 if(QueueEmpty())
 {
  cout<<"Error:Queue Empty!"<<endl;
  return false;
 }

 if(s2.StackEmpty())
 {
  while(!s1.StackEmpty())
  {
   int a;
   s1.Pop(a);
   s2.Push(a);
  }

 }

 s2.Pop(e);
 return true;
}

void main()
{
 Queue q;
 q.EnQueue(1);
 q.EnQueue(2);
 q.EnQueue(3);
 q.EnQueue(4);
 q.EnQueue(5);

 int e;

 if(q.DelQueue(e))
	 cout<<e<<endl;
 if(q.DelQueue(e))
 	cout<<e<<endl;
 if(q.DelQueue(e))
 	cout<<e<<endl;
 if(q.DelQueue(e))
 	cout<<e<<endl;
 if(q.DelQueue(e))
 	cout<<e<<endl;
 if(q.DelQueue(e))
 	cout<<e<<endl;
 if(q.DelQueue(e))
 	cout<<e<<endl;
} 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值