标签:
Implement the following operations of a stack using queues.
push to back
, peek/pop from front
, size
, and is empty
operations are valid.
Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.
1 #include<iostream> 2 #include<queue> 3 using namespace std; 4 5 queue<int> qu1; 6 7 // Push element x onto stack. 8 void push(int x) { 9 qu1.push(x); 10 } 11 12 // Removes the element on top of the stack. 13 void pop() { 14 if(!qu1.empty()) 15 { 16 int n=qu1.size()-1; 17 int re; 18 while(n--) 19 { 20 re=qu1.front(); 21 qu1.pop(); 22 qu1.push(re); 23 } 24 qu1.pop(); 25 } 26 else 27 return; 28 } 29 30 // Get the top element. 31 int top() { 32 int n=qu1.size(); 33 int re; 34 int res; 35 while(n--) 36 { 37 re=qu1.front(); 38 if(n==0) 39 res=re; 40 qu1.pop(); 41 qu1.push(re); 42 } 43 return res; 44 } 45 46 // Return whether the stack is empty. 47 bool empty() { 48 if(qu1.empty()) 49 return 1; 50 else 51 return 0; 52 } 53 54 55 int main() 56 { 57 58 }
leetcode_225题——Implement Stack using Queues (队列,栈)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4667808.html