-
Notifications
You must be signed in to change notification settings - Fork 0
/
622.设计循环队列.js
90 lines (81 loc) · 1.82 KB
/
622.设计循环队列.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
* @lc app=leetcode.cn id=622 lang=javascript
*
* [622] 设计循环队列
*/
// @lc code=start
/**
* @param {number} k
*/
var MyCircularQueue = function (k) {
this.list = new Array(k);
this.head = 0; // 头指针
this.tail = 0; // 尾指针
this.count = 0; // 元素数量
this.max = k;
};
/**
* @description 入队
* @param ∫{number} value
* @return {boolean}
*/
MyCircularQueue.prototype.enQueue = function (value) {
if (this.isFull()) return false;
this.list[this.tail] = value;
this.count += 1; // 多了一个元素
this.tail = (this.tail + 1) % this.max; // 尾指针更新
return true;
};
/**
* @description 出队
* @return {boolean}
*/
MyCircularQueue.prototype.deQueue = function () {
if (this.isEmpty()) return false;
this.list[this.head] = null;
this.head = (this.head + 1) % this.max;
this.count -= 1;
return true;
};
/**
* @return {number}
*/
MyCircularQueue.prototype.Front = function () {
if (this.isEmpty()) return -1;
return this.list[this.head]; // 返回顶部元素
};
/**
* @return {number}
*/
MyCircularQueue.prototype.Rear = function () {
if (this.isEmpty()) return -1;
// if (tail === 0) {
// tail = this.max - 1;
// } else {
// tail -= 1;
// }
return this.list[(this.tail - 1 + this.max) % this.max];
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.isEmpty = function () {
return this.count === 0;
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.isFull = function () {
return this.count === this.max;
};
/**
* Your MyCircularQueue object will be instantiated and called as such:
* var obj = new MyCircularQueue(k)
* var param_1 = obj.enQueue(value)
* var param_2 = obj.deQueue()
* var param_3 = obj.Front()
* var param_4 = obj.Rear()
* var param_5 = obj.isEmpty()
* var param_6 = obj.isFull()
*/
// @lc code=end