Smaller Python数据结构:自己动手实现队列

简介: Smaller Python数据结构:自己动手实现队列

简说Python,号主老表,Python终身学习者,数据分析爱好者,从18年开始分享Python知识,原创文章227篇,写过Python、SQL、Excel入门文章,也写过Web开发、数据分析文章,老表还总结整理了一份2022Python学习资料和电子书资源,关注后私信回复:2022 即可领取。

今天给大家分享的书籍《Python程序员面试算法宝典》第二章第二小节:如何实现队列。

如果你是第一次看,也许,你可以看看本系列下面的文章:

Python数据结构:链表合集(12+7),复现几遍,包你学会

Smaller And Smarter Python数据结构:自己动手实现栈

今日问题

"""
目标:实现队列,使其具有方法:入队列(push_queue)、出队列(pop_queue)、
取队列首元素(get_top)、取队列尾元素(get_tail)、判断队列是否为空(is_empty)、
获取队列中元素个数(size)
为后面操作打基础
Goal: To implement the queue, there are methods: push queue, pop queue,
 get top, get tail, judge whether the queue is empty, and get the number 
 of elements in the queue
Lay a foundation for later operations
"""

解题

方法一:数组(列表)实现队列

"""
Method One : 数组(列表)实现队列
核心思想:以数组(列表)作为存储队列数据的数据结构,Python里本身
对列表有着丰富的内置操作,比如pop,append,len等等,列表是顺序
存储,并且在Python初始化一个列表时,不一定非要指定列表长度,这
使得Python列表实现起来非常简单和方便。
注意:一般在C、Java中初始化数组(列表)时,是必须声明数组(列表)
长度的,而在Python中,可以不限定,但append添加的效率很明显要比
直接赋值(比如:list[1] = "Python")的低很多。
问题:用数组实现队列最大的问题就是,当出队列时,front是只向后移的,
所以会浪费前面的空间,对于这个问题,我们可以把数组看成一个环状的空
间,我记得当时我学数据结构的时候是固定数组长度,然后取余来判断数组
队列是否溢出或者该循环了。
Method one: array (list) implementation queue
Core idea: Taking array (list) as the data structure of queue data storage,
 python itself has rich built-in operations on list, such as pop, append, 
 len, etc. list is sequential storage, and when Python initializes a list, 
 it is not necessary to specify the length of list, which makes Python list 
 implementation very simple and convenient.
Note: when initializing arrays (lists) in C and Java, the length of arrays
 (lists) must be declared. In Python, there is no limit, but the efficiency
 of adding append is obviously lower than that of direct assignment (for 
 example: list [1] = "Python").
 Problem: the biggest problem of using array to realize queue
 is that when out of queue, front only moves backward, so it 
 will waste the previous space. For this problem, we can regard 
 array as a circular space. I remember that when I studied data 
 structure, I fixed the length of array, and then took the remainder 
 to judge whether the array queue overflowed or the cycle was over.
"""

代码

class ListQueue:
    def __init__(self):
        self.queue = []
        self.front = 0  # 队列头
        self.rear = 0  # 队列尾
    # 新元素进入队列
    def queue_push(self, x):
        self.queue.append(x)  # 入队列
        self.rear += 1  # 有新数据进队列,尾元素往后一个位置后移一位
        print("********入队列成功********")
    # 删除队头元素
    def queue_pop(self):
        if self.front < self.rear:
            self.front += 1  # 出队列,把队首元素记录位置后移一位
            print("********出队列成功********")
        else:
            print("********队列已空********")
    # 获取队列首元素
    def get_queue_top(self):
        if self.front == self.rear:
            print("********空队列********")
            return None
        else:
            return self.queue[self.front]
    # 获取队列尾元素
    def get_queue_tail(self):
        if self.front == self.rear:
            print("********空队列********")
            return None
        else:
            return self.queue[self.rear - 1]
    # 判断队列是否为空
    def queue_is_empty(self):
        if self.front == self.rear:
            return True
        else:
            return False
    # 队列长度
    def queue_len(self):
        return self.rear - self.front

方法二:链表实现队列

"""
Method Two : 链表实现队列
核心思想:以链表作为存储队列数据的数据结构,Python里本身
是不含链表这种数据结构的,所以需要我们自己去写对链表的基
本操作,当然在上一章中我们已经非常熟悉链表了,所以操作起
来还是很简单。
注意:Python内置的数据结构里没有链表,我们一般用引用实现
链表这一数据结构,创建一个类LinkNode,包含两个属性,data
为数据域,存放当前结点数据,next为指针域。存放下一个结点的
地址(指针)。
Method two: linked list implementation queue
Core idea: take linked list as the data structure to store queue data.
 Python itself does not contain linked list, so we need to write the
  basic operation of linked list. Of course, in the previous chapter, 
  we are very familiar with linked list, so the operation is very simple.
Note: there is no linked list in Python's built-in data structure. Generally,
 we use reference to implement the linked list data structure. We create a 
 linknode class, which contains two attributes. Data is the data field, which 
 stores the current node data, and next is the pointer field. Store the 
 address (pointer) of the next node.
"""

代码

class LinkNode:
    def __init__(self, x):
        self.data = x  # 数据域
        self.next = None  # 指针域
class LinkQueue:
    def __init__(self):
        self.pHead = None  # 队列头指针
        self.pEnd = None  # 队列尾指针
    # 入队列
    def queue_push(self, x):
        node = LinkNode(x)  # 新建一个结点
        if not self.pHead:  # 第一次有元素入队列
            self.pHead = node
            self.pEnd = node
        else:
            self.pEnd.next = node  # 添加队列末尾
            self.pEnd = node  # 尾指针后移
        print("********入队列成功********")
    # 出队列
    def queue_pop(self):
        if self.pHead:
            self.pHead = self.pHead.next
            print("********出队列成功********")
        else:
            print("********队列已空********")
    # 获取队列顶元素
    def get_queue_top(self):
        if not self.pHead:
            print("********空队列********")
            return None
        else:
            return self.pHead.data
    # 判断队列是否为空
    def queue_is_empty(self):
        if not self.pHead:
            return True
        else:
            return False
    # 获取队列尾元素
    def get_queue_tail(self):
        if not self.pHead:
            print("********空队列********")
            return None
        else:
            return self.pEnd.data
    # 队列长度
    def queue_len(self):
        link_len = 0
        cur_node = self.pHead
        while cur_node:  # 遍历计算链表长,即队列长
            cur_node = cur_node.next
            link_len = link_len + 1
        return link_len

测试代码

# 当然,也许还有别的方法,比如建一个辅助的链表
# 欢迎你说出你的想法
# 程序入口,测试函数功能
if __name__ == "__main__":
    # 初始化一个队列
    # my_queue = ListQueue()  # 列表队列测试
    my_queue = LinkQueue()  # 链表队列测试
    # 入队列
    my_queue.queue_push(1)
    my_queue.queue_push(2)
    my_queue.queue_push(4)
    # 获取队列顶
    print("当前队列顶为:", my_queue.get_queue_top())
    # 获取队列尾
    print("当前队列尾为:", my_queue.get_queue_tail())
    # 出队列
    my_queue.queue_pop()
    # 判断队列是否为空
    if my_queue.queue_is_empty():
        print("********队列已空********")
    else:
        print("********队列没空********")
    # 队列长
    print("队列长为:", my_queue.queue_len())
    # 出队列
    my_queue.queue_pop()
    my_queue.queue_pop()
    # 判断队列是否为空
    if my_queue.queue_is_empty():
        print("********队列已空********")
    else:
        print("********队列没空********")

运行结果

image.png

本文代码思路来自书籍《Python程序员面试宝典》,书中部分代码有问题,文中已经修改过了,并添加上了丰厚的注释,方便大家学习,后面我会把所有内容开源放到Github上,包括代码,思路,算法图解(手绘或者电脑画),时间充裕的话,会录制视频。希望大家多多支持。

大家好,我是老表

觉得本文不错的话,转发、留言、点赞,是对我最大的支持。

欢迎关注微信公众号:简说Python

关注后回复:1024,可以领取精选编程学习电子书籍。

相关文章
|
Java 数据挖掘 数据处理
(Pandas)Python做数据处理必选框架之一!(一):介绍Pandas中的两个数据结构;刨析Series:如何访问数据;数据去重、取众数、总和、标准差、方差、平均值等;判断缺失值、获取索引...
Pandas 是一个开源的数据分析和数据处理库,它是基于 Python 编程语言的。 Pandas 提供了易于使用的数据结构和数据分析工具,特别适用于处理结构化数据,如表格型数据(类似于Excel表格)。 Pandas 是数据科学和分析领域中常用的工具之一,它使得用户能够轻松地从各种数据源中导入数据,并对数据进行高效的操作和分析。 Pandas 主要引入了两种新的数据结构:Series 和 DataFrame。
981 0
|
前端开发 Java
java实现队列数据结构代码详解
本文详细解析了Java中队列数据结构的实现,包括队列的基本概念、应用场景及代码实现。队列是一种遵循“先进先出”原则的线性结构,支持在队尾插入和队头删除操作。文章介绍了顺序队列与链式队列,并重点分析了循环队列的实现方式以解决溢出问题。通过具体代码示例(如`enqueue`入队和`dequeue`出队),展示了队列的操作逻辑,帮助读者深入理解其工作机制。
890 1
|
存储 开发者 索引
Python 中常见的数据结构
这些数据结构各有特点和适用场景,在不同的编程任务中发挥着重要作用。开发者需要根据具体需求选择合适的数据结构,以提高程序的效率和性能
749 156
|
存储 算法 搜索推荐
Python 中数据结构和算法的关系
数据结构是算法的载体,算法是对数据结构的操作和运用。它们共同构成了计算机程序的核心,对于提高程序的质量和性能具有至关重要的作用
678 153
|
存储 开发者 Python
Python 中的数据结构与其他编程语言数据结构的区别
不同编程语言都有其设计理念和应用场景,开发者需要根据具体需求和语言特点来选择合适的数据结构
827 151
|
存储 索引 Python
Python编程数据结构的深入理解
深入理解 Python 中的数据结构是提高编程能力的重要途径。通过合理选择和使用数据结构,可以提高程序的效率和质量
693 156
|
存储 C语言 C++
【C++数据结构——栈与队列】顺序栈的基本运算(头歌实践教学平台习题)【合集】
本关任务:编写一个程序实现顺序栈的基本运算。开始你的任务吧,祝你成功!​ 相关知识 初始化栈 销毁栈 判断栈是否为空 进栈 出栈 取栈顶元素 1.初始化栈 概念:初始化栈是为栈的使用做准备,包括分配内存空间(如果是动态分配)和设置栈的初始状态。栈有顺序栈和链式栈两种常见形式。对于顺序栈,通常需要定义一个数组来存储栈元素,并设置一个变量来记录栈顶位置;对于链式栈,需要定义节点结构,包含数据域和指针域,同时初始化栈顶指针。 示例(顺序栈): 以下是一个简单的顺序栈初始化示例,假设用C语言实现,栈中存储
1448 77
|
存储 监控 安全
企业上网监控系统中红黑树数据结构的 Python 算法实现与应用研究
企业上网监控系统需高效处理海量数据,传统数据结构存在性能瓶颈。红黑树通过自平衡机制,确保查找、插入、删除操作的时间复杂度稳定在 O(log n),适用于网络记录存储、设备信息维护及安全事件排序等场景。本文分析红黑树的理论基础、应用场景及 Python 实现,并探讨其在企业监控系统中的实践价值,提升系统性能与稳定性。
967 1
|
存储 缓存 监控
局域网屏幕监控系统中的Python数据结构与算法实现
局域网屏幕监控系统用于实时捕获和监控局域网内多台设备的屏幕内容。本文介绍了一种基于Python双端队列(Deque)实现的滑动窗口数据缓存机制,以处理连续的屏幕帧数据流。通过固定长度的窗口,高效增删数据,确保低延迟显示和存储。该算法适用于数据压缩、异常检测等场景,保证系统在高负载下稳定运行。 本文转载自:https://www.vipshare.com
715 66

热门文章

最新文章

推荐镜像

更多