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

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

leetcode225. 用队列实现栈

發(fā)布時(shí)間:2023/12/4 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode225. 用队列实现栈 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一:題目

二:上碼

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

總結(jié)

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

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。