1. Stack
- FILO (FirstInLastOut) 的链表结构
- 在程序编译环境上使用较多
- 常用操作
- push
- pop
- peek
- is_empty
- size
- Python 代码示例
class Stack(object):
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.items)
if __name__ == "__main__":
stack = Stack()
print(stack.is_empty())
stack.push('a')
stack.push('b')
stack.push('c')
print(stack.size())
print(stack.peek())
print(stack.pop())
print(stack.pop())
print(stack.pop())
2. Queue
- FIFO (FirstInFastOut) 的链表结构
- 处理消息的时候使用比较多
- 生产者消费者模型
- 常用操作
- enqueue
- dequeue
- is_empty
- size
- Python 代码示例
class Queue(object):
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
if __name__ == "__main__":
queue = Queue()
print(queue.is_empty())
queue.enqueue('a')
queue.enqueue('b')
queue.enqueue('c')
print(queue.size())
print(queue.dequeue())
print(queue.dequeue())
print(queue.dequeue())
原文地址:https://www.cnblogs.com/yorkyu/p/11967304.html
时间: 2024-10-30 05:48:52