劍指offer——兩個棧實現佇列與兩個佇列實現棧
阿新 • • 發佈:2019-01-04
題目描述:兩個棧實現佇列
解題思路:棧是“先進後出”,佇列是“先進先出”。操作“入佇列”:利用兩個棧s1和s2,元素進的時候,放入s1即可。操作“出佇列”:先檢查s2是否為空,如果不為空,直接pop出s2的元素,如果為空,則把s1的元素都pop出來,然後依次放入s2中,再對s2進行pop即可。
class Solution { public: void push(int node) { stack1.push(node); } int pop() { if(stack2.empty()) { while(!stack1.empty()) { int n=stack1.top(); stack1.pop(); stack2.push(n); } } int n=stack2.top(); stack2.pop(); return n; } private: stack<int> stack1; stack<int> stack2; };
題目描述:兩個佇列實現一個棧
解題思路:對於兩個佇列,把一個作為輸入輸出佇列,另一個作為中轉佇列。兩個佇列q1和q2,輸入都放在q1,輸出時,除了q1中最後一個元素,其他都放到q2中,當輸出q1中最後一個元素後,再把q2中的元素都放回q1。
#include <iostream> #include <vector> #include <stack> #include <queue> using namespace std; class STACK { public: void push(int node) { q1.push(node); } int pop() { int sz=q1.size(); int n; for(int i=0;i<sz-1;i++) { n=q1.front(); q1.pop(); q2.push(n); } n=q1.front(); q1.pop(); while(!q2.empty()) { q1.push(q2.front()); q2.pop(); } return n; } private: queue<int> q1; queue<int> q2; }; int main() { STACK s; s.push(1); s.push(2); s.push(3); cout<<s.pop()<<endl; cout<<s.pop()<<endl; s.push(4); cout<<s.pop()<<endl; cout<<s.pop()<<endl; return 0; }