1. Title Description
Two stacks to achieve a queue, the completion queue Push and Pop operations. Queue elements int.
2. Problem-solving ideas
2.1 Analysis
Stack: last-out
queue: FIFO
- It requires two stacks {stack1, stack2} implement a queue, that is to say we need to use a stack push and pop functions to construct queues push and pop functions.
- We stack list representation, the corresponding function using the append and pop functions to achieve.
- Queue push function:
using stack1 storing element, and at this time consistent queue stack push push function - Queue pop function:
At this point want to pop out of the queue element should be the first element of the stack, so we will stack1 the elements pop out one by one from the stack tail, append to stack2, like the Tower of Hanoi, the ultimate stack2 last element of the stack It is to pop out of the elements. - Note: some stack2 divided by 2. If empty:
if at any time the stack 2 in the conventional press, then pressed to the two elements in a stack 5, 6 (1 stack states are: {5,6}), immediately to the stack in the stack 2 pressure (2 stack status: {6,5});
then again a stack 1 7 elements, elements of the stack the stack 2 is not 5,6, 7 at this time if the pressure on the stack and then the top element 2 will then 7 a variant, not removed before 5;
so in the stack 2 to complete a number of pressure elements into a stack of new elements like pressure to the stack 2 when the stack 2 to be emptied on number of elements of the job (that is, the stack 2 must be empty).
2.2 Code
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
self.stack1.append(node)
def pop(self):
if self.stack2 == []:
while self.stack1:
a = self.stack1.pop()
self.stack2.append(a)
return self.stack2.pop()
2.3 Complexity
Time complexity: O (N)
space complexity: O (N)