标签:
Implement the following operations of a queue using stacks.
push
to top
, peek/pop from top
, size
,
and is empty
operations are valid.Subscribe to see which companies asked this question
c++ code:
class Queue { public: // Push element x to the back of queue. void push(int x) { s2.push(x); } // Removes the element from in front of queue. void pop(void) { if(s1.empty()) { while(!s2.empty()){ int t = s2.top(); s2.pop(); s1.push(t); } } s1.pop(); } // Get the front element. int peek(void) { if(s1.empty()) { while(!s2.empty()){ int t = s2.top(); s2.pop(); s1.push(t); } } return s1.top(); } // Return whether the queue is empty. bool empty(void) { if(s1.empty() && s2.empty()) return true; else return false; } private: stack<int> s1,s2; };
LeetCode:Implement Queue using Stacks
标签:
原文地址:http://blog.csdn.net/itismelzp/article/details/51331386