forked from selfboot/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path232_ImplementQueueUsingStacks.py
More file actions
executable file
·46 lines (38 loc) · 1001 Bytes
/
232_ImplementQueueUsingStacks.py
File metadata and controls
executable file
·46 lines (38 loc) · 1001 Bytes
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: xuezaigds@gmail.com
class Queue(object):
"""
Use python list as the underlying data structure for stack.
Add a "move()" method to simplify code: it moves all elements
of the "inStack" to the "outStack" when the "outStack" is empty.
"""
def __init__(self):
self.in_stack, self.out_stack = [], []
def push(self, x):
self.in_stack.append(x)
def pop(self):
self.move()
self.out_stack.pop()
def peek(self):
self.move()
return self.out_stack[-1]
def empty(self):
return (not self.in_stack) and (not self.out_stack)
def move(self):
if not self.out_stack:
while self.in_stack:
self.out_stack.append(self.in_stack.pop())
'''
if __name__ == '__main__':
q = Queue()
q.push(2)
q.push(3)
q.push(4)
print q.peek()
q.pop()
print q.peek()
q.pop()
q.pop()
print q.empty()
'''