【leetcode 662】【设计循环队列】

leetcode 662【设计循环队列】

题目链接

https://leetcode-cn.com/problems/design-circular-queue/


解题思路与代码思路:

数组实现

通过头指针、队列长度、数组长度推断尾指针的位置
t a i l I n d e x = ( h e a d I n d e x + c o u n t − 1 )   m o d   c a p a c i t y tailIndex=(headIndex+count−1) \ mod \ capacity tailIndex=(headIndex+count1) mod capacity
count 是队列长度,capacity是数组长度

链表实现

head:队首元素索引,tail:队尾元素索引。掌握好指针的运用就行


代码:

数组实现
# 622 设计循环队列
def __init__(self,k):
    self.queue = [0]*k
    self.headIndex = 0
    self.count = 0
    self.capacity = k

def enQueue(self,value):
    # 判断队列是否满了
    if self.count == self.capacity:
        return False
    #在尾指针位置赋值
    self.queue[(self.headIndex + self.count)%self.capacity] = value 
    self.count +=1
    return True

def deQueue(self):
    if self.count == 0:   # rear和head相碰的时候就是等于0
        return False
    #改变头指针位置
    self.headIndex = (self.headIndex+1)%self.capacity
    self.count -= 1
    return True

def Front(self):
    if self.count == 0:
        return -1
    return self.queue[self.headIndex]

def Rear(self):
    if self.count == 0:
        return -1
    return self.queue[(self.headIndex+self.count-1)%self.capacity]

def isEmpty(self):
    return self.count == 0

def isFull(self):
    return self.count == self.capacity

链表实现
# 单链表实现
class Node:
    def __init__(self,value,nextNode=None):
        self.value = value
        self.next = nextNode
        
class myCircularQueue:
    def __init__(self,k):
        self.capacity = k
        self.head = None
        self.tail = None
        self.count = 0
    def enQueue(self,value):
        if self.count == 0:
            self.head = Node(value)
            self.tail = self.head
        else:
            newNode = Node(value)
            self.tail.next = newNode # 连接新结点
            self.tail = newNode      #移动tail指针
        self.count +=1
        return True
    
    def deQueue(self):
        if self.count == 0:
            return False
        self.head = self.head.next
        self.count -= 1
        return True
    def Front(self):
        if self.count ==0:
            return -1
        return self.head.value
    
    def Rear(self)
        if self.count ==0:
            return -1
        return self.tail.value        
    def isEmpty(self):
        return self.count == 0

    def isFull(self):
        return self.count == self.capacity

复 杂 度 分 析 : \color{red}{复杂度分析:}
  1. 两个方法
  • 时间复杂度:O(1),所有方法都具有恒定的时间复杂度。
  • 空间复杂度:O(N),与数组实现相同。但是单链表实现f方式的内存效率更高。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值