《Cracking the Coding Interview》——第3章:栈和队列——题目5

2014-03-18 05:33

题目:用两个栈来实现一个队列。

解法:栈是反的,队列是正的,反了再反就正过来了。所以,请看代码。操作中时间复杂度有O(1)的,有O(n)的,但均摊下来时间符合O(1)。

代码:

 1 // 3.5 Implement a queue MyQueue using two stacks.
 2 #include <climits>
 3 #include <cstdio>
 4 #include <cstring>
 5 #include <stack>
 6 using namespace std;
 7 
 8 template<class T>
 9 class MyQueue {
10 public:
11     bool empty() {
12         return s1.empty() && s2.empty();
13     }
14     
15     void push(const T &val) {
16         s1.push(val);
17     }
18     
19     void pop() {
20         if (s2.empty()) {
21             while (!s1.empty()) {
22                 s2.push(s1.top());
23                 s1.pop();
24             }
25         }
26         s2.pop();
27     }
28     
29     T front() {
30         if (s2.empty()) {
31             while (!s1.empty()) {
32                 s2.push(s1.top());
33                 s1.pop();
34             }
35         }
36         
37         return s2.top();
38     }
39     
40     T back() {
41         if (s1.empty()) {
42             while (!s2.empty()) {
43                 s1.push(s2.top());
44                 s2.pop();
45             }
46         }
47         
48         return s1.top();
49     }
50 private:
51     stack<T> s1, s2;
52 };
53 
54 int main()
55 {
56     MyQueue<int> qq;
57     char s[100];
58     int op;
59 
60     while (scanf("%s", s) == 1) {
61         if (strcmp(s, "end") == 0) {
62             break;
63         } else if (strcmp(s, "push") == 0) {
64             scanf("%d", &op);
65             qq.push(op);
66         } else if (strcmp(s, "pop") == 0) {
67             qq.pop();
68         } else if (strcmp(s, "front") == 0) {
69             printf("%d
", qq.front());
70         } else if (strcmp(s, "back") == 0) {
71             printf("%d
", qq.back());
72         }
73     }
74     
75     return 0;
76 }
原文地址:https://www.cnblogs.com/zhuli19901106/p/3606677.html