Title Description
Two stacks to achieve a queue, the completion queue Push and Pop operations. Queue elements int.
Time limit: C / C ++ 1 second, 2 seconds languages other
space restrictions: C / C ++ 32M, 64M other languages
Problem-solving ideas
Stack features: advanced after
the queue: FIFO
using the stack queue, that is, each time the stack, the stack can reverse the order of elements in, then the introduction of a middle stack can be easily implemented.
Two stacks (an enqueue, a dequeue):
enqueue operation: an element onto the stack a
dequeue operation: 1. The element stack pop, pushed onto the stack 2 in turn, so that the bottom of the stack the stack 1 will It became the stack top of the stack 2, 2 stack to stack again.
* Note, the laws of logic out of the team, to stack elements 1 poured into the stack 2, we must first ensure that the stack 2 empty.
Source
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int val;
if(stack2.empty())
{
int k;
while(!stack1.empty())
{
k=stack1.top();
stack2.push(k);
stack1.pop();
}
}
val=stack2.top();
stack2.pop();
return val;
}
private:
stack<int> stack1;
stack<int> stack2;
};
supplement
The basic usage of the original method of c ++ stack:
- push (): a stack to push the inner member;
- pop (): a member of the pop from the stack;
- empty (): If the stack is empty return true, otherwise return false;
- top (): Returns the top of the stack, but do not remove members;
- size (): Returns the size in the stack elements;
c ++ stack when defining its pop () pop-up members are not directly get its worth, you need to get top of the stack with the top (), then pop () pop.