1、栈
class Stack(object): """栈""" def __init__(self): self._list = [] def push(self, item): """添加一个新的元素item到栈顶""" self._list.append(item) def pop(self): """弹出栈顶元素""" return self._list.pop() def peek(self): """返回栈顶元素""" if self._list: return self._list[-1] else: return def is_empty(self): """判断栈是否为空""" return self._list == [] # 也可以用return not self._list,如果列表为空则为False,not False就是True,最后返回True,表示该列表是空 def size(self): """返回栈的元素个数""" return len(self._list) if __name__ == "__main__": s = Stack() s.push(1) s.push(2) s.push(3) s.push(4) print(s.size()) print(s.pop())
2、队列
class Queue(object): """队列""" def __init__(self): self._list = [] def enqueue(self, item): """往队列中填加一个item元素""" self._list.append(item) def dequeue(self): """从队列头部删除一个元素""" return self._list.pop(0) def is_empty(self): """判断队列是否为空""" return self._list == [] def size(self): """返回队列的大小""" return len(self._list) if __name__ == "__main__": s = Queue() s.enqueue(1) s.enqueue(2) s.enqueue(3) s.enqueue(4) print(s.size()) print(s.is_empty()) print(s.dequeue())
3、双端队列
class Deque(object): """双端队列""" def __init__(self): self.items = [] def is_empty(self): """判断队列是否为空""" return self.items == [] def add_front(self, item): """在队头添加元素""" self.items.insert(0, item) def add_rear(self, item): """在队尾添加元素""" self.items.append(item) def remove_front(self): """从队头删除元素""" return self.items.pop(0) def remove_rear(self): """从队尾删除元素""" return self.items.pop() def size(self): """返回队列大小""" return len(self.items) if __name__ == "__main__": deque = Deque() deque.add_front(1) deque.add_front(2) deque.add_rear(3) deque.add_rear(4) print(deque.is_empty()) print(deque.size()) print(deque.remove_front()) print(deque.remove_rear())