Python之栈和队列

简介: 笔记


15.png

列表实现栈


class Stack:
    def __init__(self):
        self.__list = []
    def push(self, val) -> bool:
        self.__list.append(val)
    def pop(self) -> int:
        if self.empty():
            return -1
        return self.__list.pop()
    def top(self) -> int:
        if self.empty():
            return -1
        return self.__list[-1]
    def size(self) -> int:
        return len(self.__list)
    def empty(self) -> bool:
        return self.size() == 0

队列


16.png

用列表实现队列

class Queue:
    def __init__(self):
        self.__list = []
    # 尾入队
    def push_back(self, val):
        self.__list.append(val)
    # 头入队    
    def push_front(self, val):
        self.__list.insert(0, val) 
    # 尾出队    
    def pop_back(self) -> int:
        if self.empty():
            return -1
        return self.__list.pop()
    # 头出队
    def pop_front(self) -> int:
        if self.empty():
            return -1
        return self.__list.pop(0)
    def front(self) -> int:
        if self.empty():
            return -1
        return self.__list[0]
    def size(self) -> int:
        return len(self.__list)
    def empty(self) -> bool:
        return self.size() == 0
相关文章
|
1天前
|
安全 开发者 Python
python队列(Queue)
python队列(Queue)
257 1
|
1天前
|
Python
Python实现数据结构(如:链表、栈、队列等)。
Python实现数据结构(如:链表、栈、队列等)。
258 0
|
1天前
|
存储 缓存 算法
Python中collections模块的deque双端队列:深入解析与应用
在Python的`collections`模块中,`deque`(双端队列)是一个线程安全、快速添加和删除元素的双端队列数据类型。它支持从队列的两端添加和弹出元素,提供了比列表更高的效率,特别是在处理大型数据集时。本文将详细解析`deque`的原理、使用方法以及它在各种场景中的应用。
|
1天前
|
前端开发 Python
Python中如何用栈实现队列
Python中如何用栈实现队列
214 0
|
1天前
|
存储 Python
Python中栈的概念和使用
Python中栈的概念和使用
35 0
|
1天前
|
消息中间件 监控 NoSQL
一文读懂python分布式任务队列-celery
celery是一个简单,灵活、可靠的分布式任务执行框架,可以支持大量任务的并发执行。celery采用典型生产者和消费者模型。生产者提交任务到任务队列,众多消费者从任务队列中取任务执行【2月更文挑战第11天】
55821 5
|
1天前
|
C++ Python Java
Python每日一练(20230424) 滑动窗口最大值、栈实现队列、直线上最多的点数
Python每日一练(20230424) 滑动窗口最大值、栈实现队列、直线上最多的点数
548 0
Python每日一练(20230424) 滑动窗口最大值、栈实现队列、直线上最多的点数
|
1天前
|
Go Python 算法
Python每日一练(20230412) 队列实现栈、二叉树序列化、交换链表节点
Python每日一练(20230412) 队列实现栈、二叉树序列化、交换链表节点
743 0
Python每日一练(20230412) 队列实现栈、二叉树序列化、交换链表节点
|
6月前
|
存储 算法 Python
python算法(二)—栈、队列、链表、哈希
python算法(二)—栈、队列、链表、哈希
55 0
|
1天前
|
网络协议 Unix Python
Python编程-----网络通信
Python编程-----网络通信
8 1