Skip to content

Commit 0f054e7

Browse files
committed
Update: Circular Queue
1 parent 397ab29 commit 0f054e7

1 file changed

Lines changed: 17 additions & 12 deletions

File tree

‎LeetCode/2.Medium/622.cpp‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,17 @@ using namespace std;
44

55
/*
66
Constructor:
7-
Approach: Dynamic Array Initialization
7+
Approach: Vector initialization
88
TC: O(1)
99
SC: O(1)
1010
1111
enQueue:
12-
Approach: Wraparound vector push_back
12+
Approach: Wraparound Modulo Insertion
1313
TC: O(1)
1414
SC: O(1)
1515
1616
deQueue:
17-
Approach: Wrapaound vector pop_front
17+
Approach: Wrapaound Modulo Deletion
1818
TC: O(1)
1919
SC: O(1)
2020
@@ -43,31 +43,36 @@ class MyCircularQueue {
4343
vector<int> arr;
4444
int front;
4545
int rear;
46-
int limit;
46+
int size;
47+
int cap;
4748
public:
4849
MyCircularQueue(int k) {
49-
front=rear=0;
50-
limit=k+1;
51-
arr=vector<int>(limit);
50+
front=0;
51+
rear=-1;
52+
size=0;
53+
cap=k;
54+
arr=vector<int>(cap);
5255
}
5356
bool enQueue(int value) {
5457
if(isFull()) return false;
58+
rear=(rear+1)%cap;
5559
arr[rear]=value;
56-
rear=(rear+1)%limit;
60+
size++;
5761
return true;
5862
}
5963
bool deQueue() {
6064
if(isEmpty()) return false;
61-
front=(front+1)%limit;
65+
front=(front+1)%cap;
66+
size--;
6267
return true;
6368
}
6469
int Front() { return isEmpty()?-1:arr[front]; }
6570
int Rear() {
6671
if(isEmpty()) return -1;
67-
return !rear?arr[limit-1]:arr[rear-1];
72+
return arr[rear];
6873
}
69-
bool isEmpty() { return front==rear; }
70-
bool isFull() { return (rear+1)%limit==front; }
74+
bool isEmpty() { return !size; }
75+
bool isFull() { return size==cap; }
7176
};
7277

7378
int main() {

0 commit comments

Comments
 (0)