LeetCode刷题记录12——232. Implement Queue using Stacks(easy)
LeetCode刷題記錄12——232. Implement Queue using Stacks(easy)
目錄
LeetCode刷題記錄12——232. Implement Queue using Stacks(easy)
前言
題目
語言
思路
源碼
后記
前言
從今天開始學習用C++來打代碼(身邊的ACM大佬比賽都用C++),雖然已經(jīng)學習過C和Java了,但是在寫的時候,腦子里想的是面對對象,寫來寫去又感覺再寫C一樣。。。還是很不熟練,希望能邊學邊練。
題目
此題是關(guān)于數(shù)據(jù)結(jié)構(gòu)的,關(guān)于棧和隊列的操作,學過數(shù)據(jù)結(jié)構(gòu)的應該都知道。題目目標是用棧來實現(xiàn)隊列的操作。
語言
C++
思路
做這題得先理解棧和隊列各自的特點,總結(jié)就是一句話:棧后進先出、隊列先進先出。理解這個之后,后面就好辦多了。
用兩個棧來實現(xiàn)隊列的操作。一個s1一個s2。
-
void push(int x):實現(xiàn)進隊操作,將x放在最后。先將棧s2中的元素全部出棧、然后進棧到s1。最后再將x元素進棧到s1,這樣x就在最后面了。
-
int pop():實現(xiàn)出棧操作。先將棧s1中的元素全部出棧、然后進棧到s2。這樣之后,相當于把棧s1中的值逆序排放在s2中,這樣再去取s2中的top,其實就是隊列的頭元素。
-
int peek():返回頭元素。先將棧s1中的元素全部出棧、然后進棧到s2。取s2中的top,其實就是隊列的頭元素。
-
bool empty():判空。如果s1、s2中均為空,返回true,否則返回false。
源碼
class MyQueue {stack<int>s1;stack<int>s2;
public:/** Initialize your data structure here. */MyQueue() {}/** Push element x to the back of queue. */void push(int x) {while (!s2.empty()) {s1.push(s2.top()); s2.pop();}s1.push(x);}/** Removes the element from in front of queue and returns that element. */int pop() {int item;while (!s1.empty()) {s2.push(s1.top()); s1.pop();}s2.top();s2.pop();return item;}/** Get the front element. */int peek() {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;}
};
?
/*** 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é)
以上是生活随笔為你收集整理的LeetCode刷题记录12——232. Implement Queue using Stacks(easy)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode刷题记录11——290.
- 下一篇: LeetCode刷题记录13——705.