leetcode225. 用队列实现栈
生活随笔
收集整理的這篇文章主要介紹了
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)題。
- 上一篇: 星露谷物语彩蛋复活节攻略
- 下一篇: leetcode20. 有效的括号