LeetCode刷题记录12——232. Implement Queue using Stacks(easy)
LeetCode刷題記錄12——232. Implement Queue using Stacks(easy)
目錄
LeetCode刷題記錄12——232. Implement Queue using Stacks(easy)
前言
題目
語(yǔ)言
思路
源碼
后記
前言
從今天開始學(xué)習(xí)用C++來打代碼(身邊的ACM大佬比賽都用C++),雖然已經(jīng)學(xué)習(xí)過C和Java了,但是在寫的時(shí)候,腦子里想的是面對(duì)對(duì)象,寫來寫去又感覺再寫C一樣。。。還是很不熟練,希望能邊學(xué)邊練。
題目
此題是關(guān)于數(shù)據(jù)結(jié)構(gòu)的,關(guān)于棧和隊(duì)列的操作,學(xué)過數(shù)據(jù)結(jié)構(gòu)的應(yīng)該都知道。題目目標(biāo)是用棧來實(shí)現(xiàn)隊(duì)列的操作。
語(yǔ)言
C++
思路
做這題得先理解棧和隊(duì)列各自的特點(diǎn),總結(jié)就是一句話:棧后進(jìn)先出、隊(duì)列先進(jìn)先出。理解這個(gè)之后,后面就好辦多了。
用兩個(gè)棧來實(shí)現(xiàn)隊(duì)列的操作。一個(gè)s1一個(gè)s2。
-
void push(int x):實(shí)現(xiàn)進(jìn)隊(duì)操作,將x放在最后。先將棧s2中的元素全部出棧、然后進(jìn)棧到s1。最后再將x元素進(jìn)棧到s1,這樣x就在最后面了。
-
int pop():實(shí)現(xiàn)出棧操作。先將棧s1中的元素全部出棧、然后進(jìn)棧到s2。這樣之后,相當(dāng)于把棧s1中的值逆序排放在s2中,這樣再去取s2中的top,其實(shí)就是隊(duì)列的頭元素。
-
int peek():返回頭元素。先將棧s1中的元素全部出棧、然后進(jìn)棧到s2。取s2中的top,其實(shí)就是隊(duì)列的頭元素。
-
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();*/
后記
做這樣的棧和隊(duì)列,主要抓住其各自的特點(diǎn):棧后進(jìn)先出、隊(duì)列先進(jìn)先出。最好做的時(shí)候畫畫示意圖,就很清楚了。
總結(jié)
以上是生活随笔為你收集整理的LeetCode刷题记录12——232. Implement Queue using Stacks(easy)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode刷题记录11——290.
- 下一篇: LeetCode刷题记录13——705.