1. 栈:
- 后进先出
class Stack(object): def __init__(self): self.stack = [] def peek(self): return self.stack[len(self.stack)-1] def empty(self): return self.stack == [] def push(self, values): self.stack.append(values) return values def pop(self): try: return self.stack.pop() except IndexError as q: return None
2. 队列:
- 先进先出
class Queue(object): def __init__(self, max_len): self.len = max_len # 记录队列的最大存储量 self.index = -1 # 记录队列的索引 self.q = [] # 存储队列的数据 def push(self, values): if len(self.q) == self.len: print(‘len_q : ‘,len(self.q)) print(‘len : ‘,self.len) raise IndexError("Queue is full") else: self.index += 1 return self.q.append(values) def pop(self): if self.index == -1: raise IndexError("Queue is empty") self.index -= 1 return self.q.pop(0) q = Queue(2) for i in range(3): q.push(i) print(q.pop()) print(q.pop())
原文地址:https://www.cnblogs.com/chaoqi/p/10569023.html
时间: 2024-10-13 00:55:06