面试题 03.04. 化栈为队/面试题09. 用两个栈实现队列/232. 用栈实现队列
生活随笔
收集整理的這篇文章主要介紹了
面试题 03.04. 化栈为队/面试题09. 用两个栈实现队列/232. 用栈实现队列
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2020-05-08
1.題目描述
用兩個(gè)棧實(shí)現(xiàn)一個(gè)隊(duì)列2.題解
將一個(gè)棧用來(lái)進(jìn)行入操作,另一個(gè)進(jìn)行出操作,入棧直接入,出棧的時(shí)候如果是空的則把另一個(gè) 棧中的所有元素移動(dòng)過(guò)來(lái),再進(jìn)行出棧,否則直接出棧即可。3.代碼
面試題 03.04.
class MyQueue { public:/** Initialize your data structure here. */MyQueue() {}/** Push element x to the back of queue. */void push(int x) {s1.push(x);}/** Removes the element from in front of queue and returns that element. */int pop() {if (s2.empty()){while (!s1.empty()){int t=s1.top();s1.pop();s2.push(t);}}int r=s2.top();s2.pop();return r;}/** Get the front element. */int peek() {if (s2.empty()){while (!s1.empty()){int t=s1.top();s1.pop();s2.push(t);}}return s2.top();}/** Returns whether the queue is empty. */bool empty() {if (s1.empty()&&s2.empty()) return true;return false;}stack<int> s1,s2;// s1專門(mén)用來(lái)入棧,s2專門(mén)用來(lái)出棧 };/*** 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();*/面試題09.
class CQueue { public:CQueue() {}void appendTail(int value) {s1.push(value);}int deleteHead() {if (s1.empty()&&s2.empty()) return -1;if (s2.empty()){while (!s1.empty()){s2.push(s1.top());s1.pop();}}int t=s2.top();s2.pop();return t;}stack<int> s1,s2; };/*** Your CQueue object will be instantiated and called as such:* CQueue* obj = new CQueue();* obj->appendTail(value);* int param_2 = obj->deleteHead();*/ class MyQueue { public:/** Initialize your data structure here. */MyQueue() {}/** Push element x to the back of queue. */void push(int x) {s1.push(x);}/** Removes the element from in front of queue and returns that element. */int pop() {if (s2.empty()){while (!s1.empty()){s2.push(s1.top());s1.pop();}}int t=s2.top();s2.pop();return t;}/** Get the front element. */int peek() {if (s2.empty()){while (!s1.empty()){s2.push(s1.top());s1.pop();}}return s2.top();}/** Returns whether the queue is empty. */bool empty() {if (s1.empty()&&s2.empty()) return true;return false;}stack<int>s1,s2; };/*** 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();*/總結(jié)
以上是生活随笔為你收集整理的面试题 03.04. 化栈为队/面试题09. 用两个栈实现队列/232. 用栈实现队列的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: react笔记记录
- 下一篇: 命令行选项解析函数(C语言):getop