python实现stack(栈)和队列(queue)
栈是先进后出
队列先进先出
栈示意图(顺便治治颈椎):
队列示意图:
栈实现代码:
class Stack(object):
def __init__(self):
self.stack = []
def push(self, v):
self.stack.append(v)
def pop(self):
if self.stack:
# 推出栈
return self.stack.pop()
else:
raise LookupError("stack is empty")
def is_empty(self):
return bool(self.stack)
def top(self):
return self.stack[-1]
队列实现代码:
class Head(object):
def __init__(self):
self.right = None
self.left = None
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
class Queue(object):
def __init__(self):
self.head = Head()
def queue(self, value):
new_node = Node(value)
head = self.head
if head.right:
tmp = head.right
head.right = new_node
tmp.next = new_node
else:
head.left = head.right = new_node
def dequeue(self):
if self.is_empty():
raise LookupError('Queue is empty')
head = self.head
tmp = head.left
if head.left == head.right:
head.left = head.right = None
else:
head.left = tmp.next
return tmp.value
def is_empty(self):
return not bool(self.head.left)
def top(self):
if self.is_empty():
raise LookupError('Queue is empty')
return self.head.left.value
希望能交流更多技术,关注小白的微信公众号吧。
小白技术社