日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

Leetcode 232. 用栈实现队列 解题思路及C++实现

發布時間:2025/4/16 c/c++ 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode 232. 用栈实现队列 解题思路及C++实现 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

解題思路:

使用兩個棧,一個棧a用來存儲每一次操作得到的隊列,另一個棧b作為輔助棧。

  • 在每一次push操作的時候,先把a中排好的隊列(先進先出),依次push進棧b,所以,棧b中元素的排序就是后進先出的棧順序;
  • 然后把新的元素x push進棧b,整個棧b就是后進先出的棧順序;
  • 然后再把b中的元素依次push進棧a,得到的棧a就是先進先出的隊列順序。

?

class MyQueue {stack<int> a, b; public:/** Initialize your data structure here. */MyQueue() {// nothing to do}/** Push element x to the back of queue. */void push(int x) {while(!a.empty()){b.push(a.top());a.pop();}b.push(x);while(!b.empty()){a.push(b.top());b.pop();}}/** Removes the element from in front of queue and returns that element. */int pop() {int num = a.top();a.pop();return num;}/** Get the front element. */int peek() {return a.top();}/** Returns whether the queue is empty. */bool empty() {return a.empty();} };/*** Your MyQueue object will be instantiated and called as such:* MyQueue* obj = new MyQueue();* obj->push(x);* int param_2 = obj->pop();* int param_3 = obj->peek();* bool param_4 = obj->empty();*/

?

總結

以上是生活随笔為你收集整理的Leetcode 232. 用栈实现队列 解题思路及C++实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。