标签:
Implement the following operations of a queue using stacks.
Notes:
push to top
, peek/pop from top
, size
, and is empty
operations are valid.不难,想明白就好,貌似之前看到过这样的题目;一个栈用来存放push的东西,每次需要pop或者peek的时候,再将该栈的所有数据移到另外一个栈里。
1 class Queue { 2 public: 3 stack<int> Squeue1; 4 stack<int> Squeue2; 5 // Push element x to the back of queue. 6 void push(int x) { 7 Squeue1.push(x); 8 } 9 10 // Removes the element from in front of queue. 11 void pop(void) { 12 13 int q; 14 if(Squeue2.empty()){ 15 while(!Squeue1.empty()){ 16 q=Squeue1.top(); 17 Squeue2.push(q); 18 Squeue1.pop(); 19 } 20 } 21 Squeue2.pop(); 22 } 23 24 25 26 // Get the front element. 27 int peek(void) { 28 int p,q; 29 if(Squeue2.empty()){ 30 while(!Squeue1.empty()){ 31 q=Squeue1.top(); 32 Squeue2.push(q); 33 Squeue1.pop(); 34 } 35 } 36 p=Squeue2.top(); 37 return p; 38 } 39 40 // Return whether the queue is empty. 41 bool empty(void) { 42 if(Squeue1.empty()&&Squeue2.empty()) return true; 43 else return false; 44 45 } 46 };
leetcode Implement Queue using Stacks
标签:
原文地址:http://www.cnblogs.com/LUO77/p/4986907.html