传送门
nowcoder
leetcode
题目描述
两个栈实现一个队列,完成队列的 Push 和 Pop 操作。
队列中的元素为 int 类型。
C++ 代码 - nowcoder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public: void push(int node) { pushStack.push(node); }
int pop() { if (popStack.empty()) { while (!pushStack.empty()) { popStack.push(pushStack.top()); pushStack.pop(); } }
if (popStack.empty()) { return -1; } else { int deleteItem = popStack.top(); popStack.pop(); return deleteItem; } }
private: stack<int> pushStack; stack<int> popStack; };
|
C++ 代码 - leetcode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class CQueue { public: CQueue() {
} void appendTail(int value) { pushStack.push(value); } int deleteHead() { if (popStack.empty()) { while (!pushStack.empty()) { int t = pushStack.top(); pushStack.pop(); popStack.push(t); } }
if (popStack.empty()) { return -1; } int t = popStack.top(); popStack.pop(); return t; }
private: stack<int> pushStack, popStack; };
|