用Python实现队列和栈
队列
- 先进先出
- 只能从队列末尾插入数据
- 只能从队列头部取出数据
用python实现队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Queue(object): def __init__(self): self.data_list = []
def init_queue(self): self.data_list = []
def insert(self, data): self.data_list.append(data)
def pop(self): if len(self.data_list) == 0: return None data = self.data_list[0] del self.data_list[0] return data
def size(self): return len(self.data_list)
queue = Queue() print(queue.size()) queue.insert(1) queue.insert(2) queue.insert(3) head = queue.pop() print(head) head = queue.pop() print(head) head = queue.pop() print(head)
|
输出:
栈
- 后进先出
- 只能从尾部插入数据
- 只能从尾部取数据。
用python实现栈
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Stack(object): def __init__(self): self.data_stack = []
def init_stack(self): self.data_stack = []
def insert(self, data): self.data_stack.append(data)
def pop(self): if len(self.data_stack) == 0: return None data = self.data_stack[-1] del self.data_stack[-1] return data
def size(self): return len(self.data_stack)
stack = Stack() stack.insert(1) stack.insert(2) stack.insert(3) print(stack.size()) tail = stack.pop() print(tail) tail = stack.pop() print(tail) tail = stack.pop() print(tail) tail = stack.pop() print(tail)
|
输出: