剑指05-用两个栈实现队列

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。


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
class MyStack:
def __init__(self):
self.stack = []
def push(self, x):
self.stack.append(x)
def pop(self):
if len(self.stack) == 0:
return None
val = self.stack[-1]
self.stack = self.stack[:-1]
return val
def length(self):
return len(self.stack)

class Solution:
def __init__(self):
self.stack1 = MyStack()
self.stack2 = MyStack()
def push(self, node):
# write code here
self.stack1.push(node)
def pop(self):
# return xx
while self.stack1.length() > 0:
self.stack2.push(self.stack1.pop())
val = self.stack2.pop()
while self.stack2.length() > 0:
self.stack1.push(self.stack2.pop())
return val