设计实现双端队列。
你的实现需要支持以下操作:
- MyCircularDeque(k):构造函数,双端队列的大小为k。
- insertFront():将一个元素添加到双端队列头部。 如果操作成功返回 true。
- insertLast():将一个元素添加到双端队列尾部。如果操作成功返回 true。
- deleteFront():从双端队列头部删除一个元素。 如果操作成功返回 true。
- deleteLast():从双端队列尾部删除一个元素。如果操作成功返回 true。
- getFront():从双端队列头部获得一个元素。如果双端队列为空,返回 -1。
- getRear():获得双端队列的最后一个元素。 如果双端队列为空,返回 -1。
- isEmpty():检查双端队列是否为空。
- isFull():检查双端队列是否满了。
示例:
MyCircularDeque circularDeque = new MycircularDeque(3); // 设置容量大小为3
circularDeque.insertLast(1); // 返回 true
circularDeque.insertLast(2); // 返回 true
circularDeque.insertFront(3); // 返回 true
circularDeque.insertFront(4); // 已经满了,返回 false
circularDeque.getRear(); // 返回 3
circularDeque.isFull(); // 返回 true
circularDeque.deleteLast(); // 返回 true
circularDeque.insertFront(4); // 返回 true
circularDeque.getFront(); // 返回 4
思路:用顺序表实现双端队列,由于限定了队列的长度,所以在增加和删除的时候需要判断一下
class MyCircularDeque:
def __init__(self, k):
"""
Initialize your data structure here. Set the size of the deque to be k.
:type k: int
"""
self.item = []
self.k = k
def insertFront(self, value):
"""
Adds an item at the front of Deque. Return true if the operation is successful.
:type value: int
:rtype: bool
"""
if len(self.item) >= self.k:
return False
self.item.insert(0, value)
return True
def insertLast(self, value):
"""
Adds an item at the rear of Deque. Return true if the operation is successful.
:type value: int
:rtype: bool
"""
if len(self.item) >= self.k:
return False
self.item.append(value)
return True
def deleteFront(self):
"""
Deletes an item from the front of Deque. Return true if the operation is successful.
:rtype: bool
"""
if len(self.item) == 0:
return False
self.item.pop(0)
return True
def deleteLast(self):
"""
Deletes an item from the rear of Deque. Return true if the operation is successful.
:rtype: bool
"""
if len(self.item) == 0:
return False
self.item.pop()
return True
def getFront(self):
"""
Get the front item from the deque.
:rtype: int
"""
if len(self.item) == 0:
return -1
return self.item[0]
def getRear(self):
"""
Get the last item from the deque.
:rtype: int
"""
if len(self.item) == 0:
return -1
return self.item[-1]
def isEmpty(self):
"""
Checks whether the circular deque is empty or not.
:rtype: bool
"""
return self.item == []
def isFull(self):
"""
Checks whether the circular deque is full or not.
:rtype: bool
"""
if len(self.item) == self.k:
return True
m = MyCircularDeque(3)
print(m.insertLast(1)) # 1
print(m.insertLast(2)) # 1 2
print(m.insertLast(3)) # 1 2 3
print(m.insertLast(4)) # 1 2 3
print(m.getRear())
print(m.isFull())
print(m.deleteLast()) # 1 2
print(m.insertFront(4)) # 4 1 2
print(m.getFront())