Created
April 8, 2015 21:01
-
-
Save wtfcarlos/69d8cd463c3b286f77d0 to your computer and use it in GitHub Desktop.
MyQueueClass Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# 3.5 implement a MyQueueClass using two stacks. | |
class MyQueueClass(object): | |
def __init__(self): | |
self.s1 = [] | |
self.s2 = [] | |
self.current_stack = self.s1 | |
self.isEnqueue = True | |
def __switch(self): | |
self.isEnqueue = not self.isEnqueue | |
from_stack = self.current_stack | |
if from_stack == self.s1: | |
to_stack = self.s2 | |
else: | |
to_stack = self.s1 | |
while len(from_stack) > 0: | |
n = from_stack.pop() | |
to_stack.append(n) | |
self.current_stack = to_stack | |
def queue(self, n): | |
if not self.isEnqueue: | |
self.__switch() | |
self.current_stack.append(n) | |
def dequeue(self): | |
if self.isEnqueue: | |
self.__switch() | |
return self.current_stack.pop() | |
m = MyQueueClass() | |
m.queue(1) | |
m.queue(2) | |
m.queue(3) | |
m.queue(4) | |
m.queue(5) | |
print m.dequeue() | |
print m.dequeue() | |
print m.dequeue() | |
m.queue(6) | |
print m.dequeue() | |
print m.dequeue() | |
print m.dequeue() | |
''' | |
S1 | |
--------v | |
1 2 3 4 5 | |
S2 | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment