python栈与队列
-
栈的实现
class Stack(object): """栈""" def __init__(self): self.__item = [] def push(self,item): """添加一个新的元素item到栈顶""" self.__item.append(item) def pop(self): """弹出栈顶元素""" return self.__item.pop() def peek(self): """返回栈顶元素""" if self.__item: return self.__item[-1] else: return None def is_empty(self): """判断栈是否为空""" return self.__item == [] def size(self): """返回栈的元素个数""" return len(self.__item) if __name__ == "__main__": stack = Stack() stack.push("hello") stack.push("world") stack.push("itcast") print(stack.size()) print(stack.peek()) print(stack.pop()) print(stack.pop()) print(stack.pop()) # 运行结果 3 itcast itcast world hello
-
队列实现
class Queue(object): """队列""" def __init__(self): self.__item = [] def enqueue(self,item): """往队列中添加一个item元素""" self.__item.insert(0,item) def dequeue(self): """从队列头部删除一个元素""" if self.__item: return self.__item.pop() else: return None def is_empty(self): """判断一个队列是否为空""" return self.__item == [] def size(self): """返回队列的大小""" return len(self.__item) if __name__ == "__main__": q = Queue() q.enqueue("hello") q.enqueue("world") q.enqueue("itcast") print(q.size()) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) # 运行结果 3 hello world itcast
-
双端队列
class Deque(object): """双端队列""" def __init__(self): self.__item = [] def add_front(self,item): """从队头加入一个item元素""" self.__item.insert(0,item) def add_rear(self,item): """从队尾加入一个item元素""" self.__item.append(item) def remove_front(self): """从队头删除一个item元素""" if self.__item: return self.__item.pop(0) else: return None def remove_rear(self): """从队尾删除一个item元素""" if self.__item: return self.__item.pop() else: return None def is_empty(self): """判断双端队列是否为空""" return self.__item == [] def size(self): """返回队列的大小""" return len(self.__item) if __name__ == "__main__": deque = Deque() deque.add_front(1) deque.add_front(2) deque.add_rear(3) deque.add_rear(4) print(deque.size()) print(deque.remove_front()) print(deque.remove_front()) print(deque.remove_rear()) print(deque.remove_rear()) # 运行结果 4 2 1 4 3