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+count−1) 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}{复杂度分析:} 复杂度分析:
- 两个方法
- 时间复杂度:O(1),所有方法都具有恒定的时间复杂度。
- 空间复杂度:O(N),与数组实现相同。但是单链表实现f方式的内存效率更高。