-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmyCircularQueue.go
More file actions
68 lines (60 loc) · 1.62 KB
/
myCircularQueue.go
File metadata and controls
68 lines (60 loc) · 1.62 KB
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
package stack
// MyCircularQueue struct
type MyCircularQueue struct {
queue []int
front int
rear int
size int
capacity int
}
// Constructor Initialize your data structure here. Set the size of the queue to be k. */
func Constructor(k int) MyCircularQueue {
return MyCircularQueue{
queue: make([]int, k),
front: 0,
rear: 0,
size: 0,
capacity: k,
}
}
// EnQueue Insert an element into the circular queue. Return true if the operation is successful. */
func (this *MyCircularQueue) EnQueue(value int) bool {
if this.IsFull() {
return false
}
this.queue[this.rear] = value
this.rear = (this.rear + 1 + this.capacity) % this.capacity
this.size++
return true
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
func (this *MyCircularQueue) DeQueue() bool {
if this.IsEmpty() {
return false
}
this.front = (this.front + 1 + this.capacity) % this.capacity
this.size--
return true
}
/** Get the front item from the queue. */
func (this *MyCircularQueue) Front() int {
if this.IsEmpty() {
return -1
}
return this.queue[this.front]
}
/** Get the last item from the queue. */
func (this *MyCircularQueue) Rear() int {
if this.IsEmpty() {
return -1
}
return this.queue[(this.rear-1+this.capacity)%this.capacity]
}
// IsEmpty Checks whether the circular queue is empty or not. */
func (this *MyCircularQueue) IsEmpty() bool {
return this.front == this.rear && this.size == 0
}
// IsFull Checks whether the circular queue is full or not. */
func (this *MyCircularQueue) IsFull() bool {
return this.front == this.rear && this.size == this.capacity
}