topic
train of thought
push
Operation: Insert the data into the normal stack1
operation
pop
: It is to stack1
import all the data in the middle stack2
and then pop up stack2
the head, so
- If it is not empty, the top element of the stack
stack2
will be popped directlystack2
- Otherwise, first
stack1
import the elements of
Simulate it and it will be clear
the code
class Solution {
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int ret;
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.top());
stack1.pop();
}
ret = stack2.top();
stack2.pop();
} else {
ret = stack2.top();
stack2.pop();
}
return ret;
}
private:
stack<int> stack1;
stack<int> stack2;
};
other
Likou also uses queues to implement stacks, and it is best to write them in C.