栈
class Node:
def __init__(self, data=None):
self.next = None
self.data = data
class Stack:
def __init__(self):
'''初始化'''
self.top = None
self.size = 0
def push(self, data):
'''将元素压入栈内'''
node = Node(data)
if self.top:
node.next = self.top
self.top = node
else:
self.top = node
self.size += 1
def pop(self):
'''弹出栈顶元素'''
if self.top:
data = self.top.data
self.size -= 1
if self.top.next:
self.top = self.top.next
else:
self.top = None
return data
else:
return None
def peek(self):
'''查看栈顶元素'''
if self.top:
return self.top.data
else:
return None
队列
class Node:
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class Queue:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def enqueue(self, data):
'''入队'''
new_node = Node(data, None, None)
if self.head is None:
self.head = new_node
self.tail = self.head
else:
new_node.prev = self.tail
self.tail.next = new_node
self.tail = new_node
self.size += 1
def dequeue(self):
'''出队'''
current = self.head
if self.size == 1:
self.size -= 1
self.head = None
self.tail = None
elif self.size > 1:
self.head = self.head.next
self.head.prev = None
self.size -= 1
def iter(self):
'''遍历队列'''
current = self.head
while current:
data = current.data
current = current.next
yield data