Deque is the abbreviation of double-ended queue. Since we can modify the deque on both sides, it could be used for implementing stack and queue.
The underlying implementation for deque is beautiful, from my perspective. We can image a deque as a double-ended linked list. Each container/node/block stores a separate fixed size array/list and points two pointer to its left and right block. Meanwhile, the container should maintain a index array to store the first address.
classMyCircularDeque: def__init__(self, k: int): """ Initialize your data structure here. Set the size of the deque to be k. """ self.maxlength = k self.deque = [None] * 2 * k self.left = k // 2 + 1 self.right = k // 2
1 2 3 4 5 6 7 8 9 10 11 12 13
definsertFront(self, value: int) -> bool: """ Adds an item at the front of Deque. Return true if the operation is successful. """ if self.right - self.left < self.maxlength - 1: if self.left == 0: newblock = [None] * len(self.deque) self.deuqe = newblock + self.deque self.left -= 1 self.deque[self.left] = value returnTrue else: returnFalse
1 2 3 4 5 6 7 8 9 10 11 12 13
definsertLast(self, value: int) -> bool: """ Adds an item at the rear of Deque. Return true if the operation is successful. """ if self.right - self.left < self.maxlength - 1: if self.right == len(self.deque) - 1: newblock = [None] * len(self.deque) self.deque = self.deque + newblock self.right += 1 self.deque[self.right] = value returnTrue else: returnFalse
1 2 3 4 5 6 7 8 9
defdeleteFront(self) -> bool: """ Deletes an item from the front of Deque. Return true if the operation is successful. """ if self.isEmpty(): returnFalse self.deque[self.left] = None self.left += 1 returnTrue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defdeleteLast(self) -> bool: """ Deletes an item from the rear of Deque. Return true if the operation is successful. """ if self.isEmpty(): returnFalse self.deque[self.right] = None self.right -= 1 returnTrue
defgetFront(self) -> int: """ Get the front item from the deque. """ return self.deque[self.left] if self.deque[self.left] != Noneelse-1
1 2 3 4 5
defgetRear(self) -> int: """ Get the last item from the deque. """ return self.deque[self.right] if self.deque[self.right] != Noneelse-1
1 2 3 4 5 6 7 8 9 10 11
defisEmpty(self) -> bool: """ Checks whether the circular deque is empty or not. """ return self.left == self.right+1
defisFull(self) -> bool: """ Checks whether the circular deque is full or not. """ return self.right - self.left == self.maxlength - 1