622. Design Circular Queue

Information

  • Diffculty: Medium

  • Created: 2000-01-01 00:00:00

  • Last Motified: 2000-01-01 00:00:00

Solution

#!/usr/bin/env python
# coding=utf-8
#
# Author: Lucas
# Date: 2019-08-31 21:01:03


class MyCircularQueue:

    def __init__(self, k: int):
        """
        Initialize your data structure here. Set the size of the queue to be k.
        """
        self.data = [None] * 2 * k
        self.start = 0
        self.end = 0
        self.size = k

    def enQueue(self, value: int) -> bool:
        """
        Insert an element into the circular queue. Return true if the operation is successful.
        """
        if self.end - self.start >= self.size:
            return False
        if self.end == self.size:
            for i in range(self.end - self.start):
                self.data[i] = self.data[self.start + i]
                self.data[self.start + i] = None
            self.start, self.end = 0, (self.end - self.start)
        self.data[self.end] = value
        self.end += 1
        return True

    def deQueue(self) -> bool:
        """
        Delete an element from the circular queue. Return true if the operation is successful.
        """
        if self.end == self.start:
            return False
        ans = self.data[self.start]
        self.data[self.start] = None
        self.start += 1
        return True

    def Front(self) -> int:
        """
        Get the front item from the queue.
        """
        if self.isEmpty():
            return -1
        return self.data[self.start]

    def Rear(self) -> int:
        """
        Get the last item from the queue.
        """
        if self.isEmpty():
            return -1
        return self.data[self.end - 1]

    def isEmpty(self) -> bool:
        """
        Checks whether the circular queue is empty or not.
        """
        return self.end == self.start

    def isFull(self) -> bool:
        """
        Checks whether the circular queue is full or not.
        """
        return self.end - self.start == self.size


# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue(k)
# param_1 = obj.enQueue(value)
# param_2 = obj.deQueue()
# param_3 = obj.Front()
# param_4 = obj.Rear()
# param_5 = obj.isEmpty()
# param_6 = obj.isFull()