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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

leetcode225. 用队列实现栈

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

一:題目

二:上碼

// class MyStack { // private:// queue<int> q;// public: // /** Initialize your data structure here. */ // MyStack() {// }// /** Push element x onto stack. */ // void push(int x) { // //后進 先出 反轉隊列 將新元素插到 第一個 // int size = q.size();//還沒插入新元素之前 // q.push(x); // while(size--)//保證插入的第一個元素在隊列的首位 // { // int temp = q.front(); // q.pop(); // q.push(temp);//插入到隊尾 // } // }// /** Removes the element on top of the stack and returns that element. */ // int pop() { // int popele = q.front();//訪問棧頂元素 // q.pop();//刪除棧頂元素 // return popele; // }// /** Get the top element. */ // int top() { // return q.front(); // }// /** Returns whether the stack is empty. */ // bool empty() { // return q.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(); // */class MyStack { private:/**思路:這里我們不能用兩個都隊列(一個進,一個出)來模擬棧,queue1: 1 2 3 4 queue2: 4 3 2 1移除4 (即棧頂)此時queue1: queue2: 3 2 1如果再來倆元素的話queue1: 5 6queue2:3 2 1想要移除棧頂6的話(再將隊列一的元素移到隊列二)queue2:3 2 1 6 5(可以看出無法得到 棧頂元素 6)**/queue<int> q;public:/** Initialize your data structure here. */MyStack() {}//我們將每次入隊的時候 將元素放到末尾,然后將其他元素按順序出隊排到其后面/** Push element x onto stack. */void push(int x) {int size = q.size();q.push(x);while(size--) {int temp = q.front();q.pop();q.push(temp);}}/** Removes the element on top of the stack and returns that element. */int pop() {int nums = q.front();q.pop();return nums;}/** Get the top element. */int top() {int nums = q.front();return nums;}/** Returns whether the stack is empty. */bool empty() {return q.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();*/

總結

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

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