《劍指offer》 佇列和棧

2021-10-02 18:47:29 字數 694 閱讀 3592

一、兩個棧實現乙個佇列

題目:用兩個棧來實現乙個佇列,完成佇列的push和pop操作。 佇列中的元素為int型別。

解題思路:用乙個棧來存,另乙個棧出。需要考慮的情況如下:

class solution

int pop()

else if(stack1.size()>0)

//出隊

res=stack2.top();

stack2.pop();

}return res;

}private:

stackstack1;

stackstack2;

};

二、兩個佇列模擬棧

解答思路:

class solution

int pop()

else

a = queue1.front();

queue1.pop();

while(!queue2.empty())

}return a;

}private:

queuequeue1;

queuequeue2;

};

棧和佇列 劍指offer

題目 定義棧的資料結構,請在該型別中實現乙個能夠得到棧最小元素的 min函式。class solution def init self self.elem def push self,node def pop self return self.elem.pop def top self return...

劍指offer 佇列和棧操作

問題1 兩個棧實現佇列 class queue 出隊 int pop int temp s2.top if s2.empty s2.pop return temp private stack s1 stack s2 問題2 兩個佇列實現棧 class stack int pop int temp q...

劍指offer 棧 佇列類題目

題目 用兩個棧來實現乙個佇列,完成佇列的push和pop操作。佇列中的元素為int型別。解析 題目中有兩個棧stack1和stack2,用來模擬佇列的操作,我是想把第乙個stack1作為資料儲存,第二個stack2作為中轉。佇列的特點是先進先出,1 入隊操作,因為用stack1作為儲存,首先得判斷上...