标签:
Implement the following operations of a queue using stacks.
Notes:
push to top
, peek/pop from top
, size
, and is empty
operations are valid.1 class Queue { 2 public: 3 // Push element x to the back of queue. 4 void push(int x) { 5 stk.push(x); 6 } 7 8 // Removes the element from in front of queue. 9 void pop(void) { 10 stack<int> temp; 11 while(stk.size()!=1){ 12 int x=stk.top(); 13 stk.pop(); 14 temp.push(x); 15 } 16 stk.pop(); 17 while(!temp.empty()){ 18 int x=temp.top(); 19 temp.pop(); 20 stk.push(x); 21 } 22 } 23 24 // Get the front element. 25 int peek(void) { 26 stack<int> temp; 27 while(stk.size()!=1){ 28 int x=stk.top(); 29 stk.pop(); 30 temp.push(x); 31 } 32 int x=stk.top(); 33 while(!temp.empty()){ 34 int x=temp.top(); 35 temp.pop(); 36 stk.push(x); 37 } 38 return x; 39 } 40 41 // Return whether the queue is empty. 42 bool empty(void) { 43 return stk.empty(); 44 } 45 private: 46 stack<int> stk; 47 };
【LeetCode】232 - Implement Queue using Stacks
标签:
原文地址:http://www.cnblogs.com/irun/p/4695636.html