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

这篇文章主要介绍了C++语言数据结构用两个栈实现一个队列的实例的相关资料,需要的朋友可以参考下

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

栈是先进后出,队列是先进先出

每次元素都push在st1中,pop的时候如果st2为空,将st1的栈顶元素放在st2的栈底,这样st1的所有元素都放在st2中,st1的栈底就是st2的栈顶,pop st2的栈顶,这样就满足了队列的先进先出。

这里写图片描述

 #include  using namespace std; #include  #include  template  class SQueue { public: void Push(const T& value); T Pop(); private: stack st1; stack st2; }; template  T SQueue::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  void SQueue::Push(const T& value) { st1.push(value); } int main() { SQueue 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; }

这里写图片描述

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

以上就是数据结构用两个栈实现一个队列的实例的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » C语言