【LeetCode 225_資料結構_棧_實現】Implement Stack using Queues

QingLiXueShi發表於2015-07-08

 1 class Stack {
 2 public:
 3     // Push element x onto stack.
 4     void push(int x) {
 5         int len = nums.size();
 6         nums.push(x);
 7         for (int i = 0; i < len; ++i) {
 8             nums.push(nums.front());
 9             nums.pop();
10         }
11     }
12 
13     // Removes the element on top of the stack.
14     void pop() {
15         nums.pop();
16     }
17 
18     // Get the top element.
19     int top() {
20         return nums.front();
21     }
22 
23     // Return whether the stack is empty.
24     bool empty() {
25         return nums.empty();
26     }
27 private:
28     queue<int> nums;
29 };

 

相關文章