Skip to content

Commit 64a1fc9

Browse files
committed
用栈实现队列
1 parent 06365d5 commit 64a1fc9

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

implement_queue_by_two_stacks.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class MyQueue:
4+
5+
def __init__(self):
6+
self.stack1 = []
7+
self.stack2 = []
8+
9+
def push(self, element):
10+
# write your code here
11+
while self.stack1:
12+
self.stack2.append(self.stack1.pop())
13+
self.stack1.append(element)
14+
while self.stack2:
15+
self.stack1.append(self.stack2.pop())
16+
17+
def top(self):
18+
# write your code here
19+
# return the top element
20+
if self.stack1:
21+
return self.stack1[-1]
22+
23+
def pop(self):
24+
# write your code here
25+
# pop and return the top element
26+
return self.stack1.pop()

0 commit comments

Comments
 (0)