源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

数据结构用两个栈实现一个队列的实例

  • 时间:2020-05-16 01:15 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:数据结构用两个栈实现一个队列的实例
[b]数据结构用两个栈实现一个队列的实例[/b] [b]栈是先进后出,队列是先进先出[/b] 每次元素都push在st1中,pop的时候如果st2为空,将st1的栈顶元素放在st2的栈底,这样st1的所有元素都放在st2中,st1的栈底就是st2的栈顶,pop st2的栈顶,这样就满足了队列的先进先出。 [img]http://files.jb51.net/file_images/article/201706/201706220917557.png[/img]
#include <iostream>
using namespace std;
#include <stack>
#include <stdlib.h>

template <class T>
class SQueue {
public:
  void Push(const T& value);
  T Pop();
private:
  stack<T> st1;
  stack<T> st2;
};

template <class T>
T SQueue<T>::Pop()
{
  if (st2.size() <= 0)
  {
    if (st1.size() == 0)
    {
      exit(1);
    }
    while ((st1.size() > 0))
    {
      T& top = st1.top();
      st2.push(top);
      st1.pop();
    }
  }

  T head = st2.top();
  st2.pop();
  return head;

}

template <class T>
void SQueue<T>::Push(const T& value)
{
  st1.push(value);
}

int main()
{
  SQueue<int> sq;
  for (int i = 0; i < 10; ++i)
  {
    sq.Push(i);
  }
  for (int i = 0; i < 5; ++i) 
  {
    cout << sq.Pop() << " ";
  }

  for (int i = 0; i < 5; ++i) //分两次验证
  {
    cout << sq.Pop() << " ";
  }
  cout << endl;

  system("pause");
  return 0;
}
[img]http://files.jb51.net/file_images/article/201706/201706220917558.png[/img] 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部