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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leetcode255用队列构造栈

發布時間:2025/4/5 编程问答 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode255用队列构造栈 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

使用隊列構造棧
題目鏈接:Leetcode225
使用隊列實現棧的下列操作:

push(x) -- 元素 x 入棧 pop() -- 移除棧頂元素 top() -- 獲取棧頂元素 empty() -- 返回棧是否為空

注意:

你只能使用隊列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 這些操作是合法的。 你所使用的語言也許不支持隊列。 你可以使用 list 或者 deque(雙端隊列)來模擬一個隊列 , 只要是標準的隊列操作即可。 你可以假設所有操作都是有效的(例如, 對一個空的棧不會調用 pop 或者 top 操作)。

解題思路:
push(x)操作要點: 隊列先進先出,模擬棧后進先出

  • 新進入隊列的元素x在隊尾,需要放在隊列的隊首位置front()
  • 使用臨時隊列temp_queue來過渡
  • 新來元素x進入temp_queue,原來隊列_data中的元素依次進入新隊列temp_queue
  • 臨時隊列再放回到原隊列_data 。
  • leetcode提交代碼如下:

    class MyStack { public:/** Initialize your data structure here. */std::queue<int> _data;MyStack() {}/** Push element x onto stack. */void push(int x) {std::queue<int> temp_queue;//臨時隊列temp_queue.push(x);//新元素x放入臨時隊列while(!_data.empty())//原隊列進臨時隊列{temp_queue.push(_data.front());//放入臨時隊列_data.pop();//從原隊列出隊}while(!temp_queue.empty())//臨時隊列回到原隊列_data{_data.push(temp_queue.front());temp_queue.pop();//臨時隊列釋放}}/** Removes the element on top of the stack and returns that element. */int pop() {int x=_data.front();_data.pop();return x;}/** Get the top element. */int top() {return _data.front();}/** Returns whether the stack is empty. */bool empty() {return _data.empty();} };/*** Your MyStack object will be instantiated and called as such:* MyStack* obj = new MyStack();* obj->push(x);* int param_2 = obj->pop();* int param_3 = obj->top();* bool param_4 = obj->empty();*/

    總結

    以上是生活随笔為你收集整理的Leetcode255用队列构造栈的全部內容,希望文章能夠幫你解決所遇到的問題。

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