diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index c7dc52f1..8b9abd35 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -72,6 +72,7 @@ class MyStack { public: queue que1; queue que2; // 辅助队列,用来备份 + /** Initialize your data structure here. */ MyStack() { @@ -100,9 +101,28 @@ public: return result; } - /** Get the top element. */ - int top() { - return que1.back(); + /** Get the top element. + ** Can not use back() direactly. + */ + int top(){ + int size = que1.size(); + size--; + while (size--){ + // 将que1 导入que2,但要留下最后一个元素 + que2.push(que1.front()); + que1.pop(); + } + + int result = que1.front(); // 留下的最后一个元素就是要回返的值 + que2.push(que1.front()); // 获取值后将最后一个元素也加入que2中,保持原本的结构不变 + que1.pop(); + + que1 = que2; // 再将que2赋值给que1 + while (!que2.empty()){ + // 清空que2 + que2.pop(); + } + return result; } /** Returns whether the stack is empty. */ @@ -126,14 +146,17 @@ C++优化代码 class MyStack { public: queue que; + /** Initialize your data structure here. */ MyStack() { } + /** Push element x onto stack. */ void push(int x) { que.push(x); } + /** Removes the element on top of the stack and returns that element. */ int pop() { int size = que.size(); @@ -147,9 +170,21 @@ public: return result; } - /** Get the top element. */ - int top() { - return que.back(); + /** Get the top element. + ** Can not use back() direactly. + */ + int top(){ + int size = que.size(); + size--; + while (size--){ + // 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部 + que.push(que.front()); + que.pop(); + } + int result = que.front(); // 此时获得的元素就是栈顶的元素了 + que.push(que.front()); // 将获取完的元素也重新添加到队列尾部,保证数据结构没有变化 + que.pop(); + return result; } /** Returns whether the stack is empty. */