leetcode225. 用队列实现栈
生活随笔
收集整理的這篇文章主要介紹了
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. 用队列实现栈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 星露谷物语彩蛋复活节攻略
- 下一篇: leetcode20. 有效的括号