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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

Leetcode232使用栈实现队列

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

題目:使用棧實現隊列。
使用棧實現隊列的下列操作:

push(x) -- 將一個元素放入隊列的尾部。 pop() -- 從隊列首部移除元素。 peek() -- 返回隊列首部的元素。 empty() -- 返回隊列是否為空。

示例:

MyQueue queue = new MyQueue();queue.push(1); queue.push(2); queue.peek(); // 返回 1 queue.pop(); // 返回 1 queue.empty(); // 返回 false

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

來源:力扣(LeetCode)
鏈接:232使用棧實現隊列

解題思路:
核心:使用棧后進先出,模擬隊列的先進先出。

  • 使用臨時堆棧temp_stack
  • 首先將原棧中元素壓入臨時棧(這時候是反向的)
  • 新來的元素x再入temp_stack
  • 臨時堆棧調入原來的棧_data(順序再次顛倒,變成正常順序)
  • Leetcode提交代碼:

    class MyQueue { public:/** Initialize your data structure here. */std::stack<int> _data;MyQueue() {}/** Push element x to the back of queue. */void push(int x) {std::stack<int> temp_stack;//臨時堆棧//if(_data.empty())//不需要這步判斷是否為空// _data.push(x);while(!_data.empty())//原堆棧數據進入臨時堆棧{temp_stack.push(_data.top());_data.pop();}temp_stack.push(x);//新來的元素進入臨時堆棧while(!temp_stack.empty())//臨時堆棧數據交給原堆棧{_data.push(temp_stack.top());temp_stack.pop();}}/** Removes the element from in front of queue and returns that element. */int pop() {//這里需要注意,返回的是一個數值int x=_data.top();//_data.pop();return x;}/** Get the front element. */int peek() {return _data.top();}/** Returns whether the queue is empty. */bool empty() {return _data.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();*/

    總結:
    這里需要總結的是pop()函數的書寫
    起初寫成:理解錯了題意,正確應該如下:pop()返回的是被出棧的那個數據。

    int pop() {_data.pop();//出棧return _data.top();//返回棧頂,這是錯誤的 }

    正確的pop()

    int pop() { int x=_data.top();_data.pop();return x;//返回被彈出的數據 }

    總結

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

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