随笔 - 5  文章 - 0  评论 - 0  阅读 - 537

数据结构预算法学习笔记 —— 双端队列(Deque)

双端队列(Deque)

1.简介

双端队列是一种有次序的数据集。

和队列相似,其两端也可以称作为”首“”尾“段,但deque中数据项既可以从队首加入,也可以从队尾加入。同样,数据项也可以从双端队列的两端移除。

某种意义上, 双端队列集合了栈和队列的特点

 

因此,双端队列并不具有内在的LIFO或者FIFO特性,如果使用双端队列来模拟栈或队列,则需要由使用者自行维护操作的一致性

 

Deque的python实现

复制代码
class Deque: # index=0 is rear, index=-1 is head
    def __init__(self):
        self.items = []
        
    def addFront(self,item): # add item to the head
        self.items.append(item)
        
    def addRear(self,item): # add item to the rear
        self.items.insert(0, item)
        
    def removeFront(self): # remove the head item and return it
        return self.items.pop()
    
    def removeRear(self): # remove the rear item and return it
        return self.items.pop(0)
    
    def isEmpty(self): 
        return self.items == []
    it
    def size(self): # return the number of items
        return len(self.items)
复制代码

 

2. Deque的应用

2.1回文判定

回文词即正读反读都一样的词,如:radar,madan,toot

判断词是否为回文词,可以先将需要判断的词加入到deque,再从两端同时判定字符是否相同。若结果为是,则删除直到字符串只剩下0或一个词

复制代码
def palChecker(aString):
    checker = Deque()

    for item in aString:
        checker. addRear(item)
    while checker.size()> 1:
        headitem = checker.removeFront()
        rearitem = checker.removeRear()
        if headitem != rearitem: return False
return True
复制代码

 

posted on   无甲的乔  阅读(44)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
< 2025年3月 >
23 24 25 26 27 28 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 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示