码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Implement Queue using Stacks

时间:2015-07-07 12:33:18      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

A classic interview question. This link has a nice explanation of the idea using two stacks and its amortized time complexity.

I use the same idea in my code, which is as follows.

 1 class Queue {
 2 public:
 3     // Push element x to the back of queue.
 4     void push(int x) {
 5         stack1.push(x);
 6     }
 7 
 8     // Removes the element from in front of queue.
 9     void pop(void) {
10         if (stack2.empty()) {
11             while (!stack1.empty()) {
12                 int elem = stack1.top();
13                 stack1.pop();
14                 stack2.push(elem);
15             }
16         }
17         stack2.pop();
18     }
19 
20     // Get the front element.
21     int peek(void) {
22         if (stack2.empty()) {
23             while (!stack1.empty()) {
24                 int elem = stack1.top();
25                 stack1.pop();
26                 stack2.push(elem);
27             }
28         }
29         return stack2.top();
30     }
31 
32     // Return whether the queue is empty.
33     bool empty(void) {
34         return stack1.empty() && stack2.empty();
35     }
36 private:
37     stack<int> stack1;
38     stack<int> stack2;
39 };

 

[LeetCode] Implement Queue using Stacks

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4626552.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!