"Sword refers to offer" with two stacks to achieve the queue problem-solving report (Python)
tags (space-delimited): Leetcode
Topic Address: Https://www.nowcoder.com/ta/coding-interviews topic Description:
Implement a queue with two stacks to complete the push and pop operations of the queue. The elements in the queue are of type int. Ways
The first stack temporarily saves the inserted data, and when the pop-up function is invoked, it pops up directly if the Stack2 is not empty, and the data in the stack1 pops up into the stack2.
This will not conflict, and because Stack2 save the old data, pop-up must conform to the rules of the queue.
#-*-Coding:utf-8-*-
class Solution:
def __init__ (self):
self.stack1 = []
self.stack2 = []
def Push (self, node):
self.stack1.append (node)
def pop (self):
if Self.stack2: Return
Self.stack2.pop ()
else: While
self.stack1:
self.stack2.append (Self.stack1.pop ()) return
Self.stack2.pop ()
Date
March 9, 2018