File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Amortized O(1)となるコードを誤解していたのを指摘されたので、書き直す。
3
+ push時にpush_stackにpop_stackから要素を移動させてくる必要はない。
4
+ pop_stackの中身が足りなくなってから(peek/pop時)push_stackの要素を移動させてくれば良く、その逆の移動は不要。
5
+ */
6
+ class MyQueue {
7
+ public:
8
+ stack<int > push_stack;
9
+ stack<int > pop_stack;
10
+
11
+ MyQueue () {}
12
+
13
+ void push (int x) {
14
+ push_stack.push (x);
15
+ }
16
+
17
+ int pop () {
18
+ int pop_value = peek ();
19
+ pop_stack.pop ();
20
+ return pop_value;
21
+ }
22
+
23
+ int peek () {
24
+ if (empty ()) {
25
+ return -1 ;
26
+ }
27
+ if (pop_stack.empty ()){
28
+ while (!push_stack.empty ()) {
29
+ pop_stack.push (push_stack.top ());
30
+ push_stack.pop ();
31
+ }
32
+ }
33
+ return pop_stack.top ();
34
+ }
35
+
36
+ bool empty () {
37
+ return push_stack.empty () && pop_stack.empty ();
38
+ }
39
+ };
40
+
41
+ /* *
42
+ * Your MyQueue object will be instantiated and called as such:
43
+ * MyQueue* obj = new MyQueue();
44
+ * obj->push(x);
45
+ * int param_2 = obj->pop();
46
+ * int param_3 = obj->peek();
47
+ * bool param_4 = obj->empty();
48
+ */
You can’t perform that action at this time.
0 commit comments