@@ -2406,59 +2406,74 @@ class MyCircularQueue:
2406
2406
def __init__ (self , k : int ):
2407
2407
"""
2408
2408
Initialize your data structure here. Set the size of the queue to be k.
2409
+ :param k:
2410
+ :return:
2409
2411
"""
2410
- self .size = k
2411
- self .data = []
2412
+ self .size = 0
2413
+ self .max_size = k
2414
+ self .data = [0 ] * k
2415
+ self .front = self .rear = - 1
2412
2416
2413
2417
def enQueue (self , value : int ) -> bool :
2414
2418
"""
2415
2419
Insert an element into the circular queue. Return true if the operation is successful.
2420
+ :param value:
2421
+ :return:
2416
2422
"""
2417
2423
if self .isFull():
2418
2424
return False
2419
-
2420
- self .data.append(value)
2425
+
2426
+ if self .rear == - 1 :
2427
+ self .rear = self .front = 0
2428
+ else :
2429
+ self .rear = (self .rear + 1 ) % self .max_size
2430
+
2431
+ self .data[self .rear] = value
2432
+ self .size += 1
2421
2433
return True
2422
2434
2423
2435
def deQueue (self ) -> bool :
2424
2436
"""
2425
2437
Delete an element from the circular queue. Return true if the operation is successful.
2438
+ :return:
2426
2439
"""
2427
2440
if self .isEmpty():
2428
2441
return False
2429
-
2430
- self .data.pop(0 )
2442
+
2443
+ if self .front == self .rear:
2444
+ self .front = self .rear = - 1
2445
+ else :
2446
+ self .front = (self .front + 1 ) % self .max_size
2447
+ self .size -= 1
2431
2448
return True
2432
2449
2433
2450
def Front (self ) -> int :
2434
2451
"""
2435
2452
Get the front item from the queue.
2453
+ :return:
2436
2454
"""
2437
- if self .isEmpty():
2438
- return - 1
2439
-
2440
- return self .data[0 ]
2455
+ return self .data[self .front] if self .size != 0 else - 1
2441
2456
2442
2457
def Rear (self ) -> int :
2443
2458
"""
2444
2459
Get the last item from the queue.
2460
+ :return:
2445
2461
"""
2446
- if self .isEmpty():
2447
- return - 1
2448
-
2449
- return self .data[- 1 ]
2450
-
2462
+ return self .data[self .rear] if self .size != 0 else - 1
2463
+
2451
2464
def isEmpty (self ) -> bool :
2452
2465
"""
2453
2466
Checks whether the circular queue is empty or not.
2467
+ :return:
2454
2468
"""
2455
- return not self .data
2469
+ return self .size == 0
2456
2470
2457
2471
def isFull (self ) -> bool :
2458
2472
"""
2459
2473
Checks whether the circular queue is full or not.
2474
+ :return:
2460
2475
"""
2461
- return len ( self .data) == self .size
2476
+ return self .size == self .max_size
2462
2477
2463
2478
2464
2479
# Your MyCircularQueue object will be instantiated and called as such:
0 commit comments