堆栈和队列

栈 (Stack)是一种后进先出(last in first off,LIFO)的数据结构

队列(Queue)则是一种先进先出 (fisrt in first out,FIFO)的结构

Stack_Queue

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
class Stack:
def __init__(self):
self.items = []

def is_empty(self):
return not self.items

def push(self, item):
"""adds a new item to the top of the stack"""
self.items.append(item)

def pop(self):
"""
removes the top item from the stack,
popping an empty stack (list) will result in an error
"""
if not self.is_empty():
return self.items.pop()
return "Pop from empty stack"

def peek(self):
"""returns the top item from the stack but does not remove it"""
if not self.is_empty():
return self.items[len(self.items) - 1]
return "Stack is Empty"

def size(self):
return len(self.items)

队列

坚持原创技术分享,您的支持将鼓励我继续创作!