我有一些堆栈代码,如下所示:
class Stack():
def init(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
return self.items.append(item)
def pop(self):
return self.items.pop()
def getElements(self):
return self.items
队列的等价物是什么?
答案 0 :(得分:1)
队列是先入先出,这很容易实现。
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
return self.items.append(item)
def pop(self):
return self.items.pop()
def get_elements(self):
return self.items
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
return self.items.append(item)
def pull(self):
return self.items.pop(0)
def get_elements(self):
return self.items
stack = Stack() # items = []
stack.push("A") # items = ["A"]
stack.push("B") # items = ["A", "B"]
stack.push("C") # items = ["A", "B", "C"]
stack.pop() # items = ["A", "B"]
queue = Queue() # items = []
queue.push("A") # items = ["A"]
queue.push("B") # items = ["A", "B"]
queue.push("C") # items = ["A", "B", "C"]
queue.pull() #items = ["B", "C"]
答案 1 :(得分:1)
不要像Java一样使用Python,为这些基本ADT定义类不是“Pythonic”,更不用说由于额外的包装而违背性能。
内置列表可以做到这一点以及更多。
堆栈是LIFO(后进先出)
>>> stack = []
# push, use append
>>> stack.append(1)
>>> stack.append(2)
>>> stack.append(3)
# pop
>>> stack.pop() # to get the last inserted element
>>>
3
# isEmpty
>>> if stack:
>>> print('not empty')
队列是FIFO(先进先出)
>>> queue = collections.deque()
# push, use append
>>> queue.append(1)
>>> queue.append(2)
>>> queue.append(3)
# pull, use popleft to get the "first" inserted element
>>> queue.popleft()
>>>
1