[关闭]
@rg070836rg 2015-08-16T15:09:27.000000Z 字数 1326 阅读 1714

双栈模拟队列

data_structure

一、简介

队列的操作,即进队和出队伍,还有判空函数,由于这里调用STL的栈,用的是deque做的容器,不存在判满。

那么,有种很容易想到的思路,从a进栈,但是由于先进来的被压在了最下面,而我以后需要第一个用的就是这个被压在底部的元素,所以,当要取得时候,把栈a倒扣,元素全部灌倒b中,把b中的第一个拿走就好了。

二、具体实现

下面说说具体的实现。

  • 首先,需要定义两个栈a,b用于元素的进出。

入队列:

  • 如果b为空,直接把元素压入a;
  • 如果b有元素,把b中元素反扣到a中,再压入元素(保证先后次序)

出队列:

  • 如果a,b都空,没有元素,提示错误。
  • 如果a空,b不空,直接弹出b的第一个元素。
  • 如果a不空,首先把a中元素反扣到b中,输出b中的第一个元素。
  • 不会出现a,b同时不空的情况

贴代码:

  1. #include <stack>
  2. using namespace std;
  3. template<class T>
  4. class StackQueue
  5. {
  6. public:
  7. StackQueue();
  8. virtual ~StackQueue();
  9. void EnQueue(T x);
  10. T DeQueue();
  11. bool IsEmpty();
  12. private:
  13. stack<T> a;
  14. stack<T> b;
  15. };
  1. template<class T>
  2. void StackQueue<T>::EnQueue(T x)
  3. {
  4. if (b.empty()) //如果栈b为空,直接压入栈a
  5. a.push(x);
  6. else //如果栈b不空,首先把元素还到栈a,再压入
  7. {
  8. while (!b.empty()) {
  9. a.push(b.top());
  10. b.pop();
  11. }
  12. a.push(x);
  13. }
  14. }
  15. template<class T>
  16. T StackQueue<T>::DeQueue()
  17. {
  18. if (IsEmpty())
  19. {
  20. cout<<"no elem"<<endl;
  21. exit(0);
  22. }
  23. if(a.empty())
  24. {
  25. T x=b.top();
  26. b.pop();
  27. return x;
  28. }
  29. while(!a.empty())
  30. {
  31. b.push(a.top());
  32. a.pop();
  33. }
  34. T x=b.top();
  35. b.pop();
  36. return x;
  37. }
  38. template<class T>
  39. bool StackQueue<T>::IsEmpty()
  40. {
  41. if(a.empty()&&b.empty())
  42. return true;
  43. else
  44. return false;
  45. }

三、测试函数

  1. int main()
  2. {
  3. StackQueue<int> SQ;
  4. //模拟顺序进栈
  5. for(int i=0; i<7; i++)
  6. SQ.EnQueue(i+2);
  7. //模拟顺序出栈
  8. cout<<"输出顺序出栈的测试"<<endl;
  9. for(int j=0; j<7; j++)
  10. cout<<SQ.DeQueue()<<" ";
  11. cout<<endl;
  12. cout<<"测试中途插入"<<endl;
  13. SQ.EnQueue(1);
  14. SQ.EnQueue(2);
  15. SQ.EnQueue(3);
  16. cout<<SQ.DeQueue()<<" ";
  17. SQ.EnQueue(4);
  18. SQ.EnQueue(5);
  19. while (!SQ.IsEmpty())
  20. {
  21. cout<<SQ.DeQueue()<<" ";
  22. }
  23. return 0;
  24. }

测试截图:
此处输入图片的描述

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注