leetcode练习:设计循环队列, python实现

做这道题踩了几个坑。

首先是要注意好逻辑结构,什么时候是空的,什么时候是非空的,什么时候enqueue和dequeue时要移动指针,什么时候不需要。

其次是注意类内变量是要在__init__内定义,而不是在__init__外定义在__init__内初始化。

最后是题目虽然说操作数在1-1000中间,但测试样例中有输入为0的情况,因此空位不能设置为0,最好设置为-1,这样front()和rear()定义不需要判断queue是否空,直接取值即可。

代码为:

class MyCircularQueue(object):

    def __init__(self, k):
        """
        Initialize your data structure here. Set the size of the queue to be k.
        :type k: int
        """
        self.queue = []
        for _ in range(k):
            self.queue.append(-1)
        self.front = 0
        self.rear = 0
        return

    def enQueue(self, value):
        """
        Insert an element into the circular queue. Return true if the operation is successful.
        :type value: int
        :rtype: bool
        """
        if self.isFull():
            return False
        elif self.front == self.rear and self.queue[self.rear] == -1:
            self.queue[self.rear] = value
            return True
        else:
            self.rear += 1
            if self.rear == len(self.queue):
                self.rear = 0
            self.queue[self.rear] = value
            return True

    def deQueue(self):
        """
        Delete an element from the circular queue. Return true if the operation is successful.
        :rtype: bool
        """
        if self.isEmpty():
            return False
        elif self.front == self.rear:
            self.queue[self.front] = -1
            return True
        else:
            self.queue[self.front] = -1
            self.front += 1
            if self.front == len(self.queue):
                self.front = 0
            return True

    def Front(self):
        """
        Get the front item from the queue.
        :rtype: int
        """
        return self.queue[self.front]

    def Rear(self):
        """
        Get the last item from the queue.
        :rtype: int
        """
        return self.queue[self.rear]

    def isEmpty(self):
        """
        Checks whether the circular queue is empty or not.
        :rtype: bool
        """
        if self.front == self.rear and self.queue[self.front] == -1:
            return True
        else:
            return False

    def isFull(self):
        """
        Checks whether the circular queue is full or not.
        :rtype: bool
        """
        rear_next = self.rear + 1
        if rear_next == len(self.queue):
            rear_next = 0
        if rear_next == self.front:
            return True


# 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()

 

你可能感兴趣的:(Leetcode练习,python初步)