- Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdesign_circular_queue.go
133 lines (114 loc) · 2.53 KB
/
design_circular_queue.go
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package main
// type MyCircularQueue struct {
// slice []int
// front, rear, size int
// }
// func Constructor(k int) MyCircularQueue {
// return MyCircularQueue{
// size: k,
// slice: make([]int, k),
// front: 0,
// rear: -1,
// }
// }
// func (q *MyCircularQueue) EnQueue(value int) bool {
// if q.IsFull() {
// return false
// }
// q.rear++
// q.slice[q.rear%q.size] = value
// return true
// }
// func (q *MyCircularQueue) DeQueue() bool {
// if q.IsEmpty() {
// return false
// }
// q.front++
// return true
// }
// func (q *MyCircularQueue) Front() int {
// if q.IsEmpty() {
// return -1
// }
// return q.slice[q.front%q.size]
// }
// func (q *MyCircularQueue) Rear() int {
// if q.IsEmpty() {
// return -1
// }
// return q.slice[q.rear%q.size]
// }
// func (q *MyCircularQueue) IsEmpty() bool {
// return q.rear < q.front
// }
// func (q *MyCircularQueue) IsFull() bool {
// return q.rear-q.front == q.size-1
// }
typeMyCircularQueuestruct {
queue []int
frontint
rearint
sizeint
}
/** Initialize your data structure here. Set the size of the queue to be k. */
funcConstructor(kint) MyCircularQueue {
returnMyCircularQueue{
queue: make([]int, k),
front: -1,
rear: -1,
size: k,
}
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
func (this*MyCircularQueue) EnQueue(valueint) bool {
ifthis.IsFull() {
returnfalse
}
this.rear= (this.rear+1) %this.size
ifthis.front==-1 {
this.front=this.rear
}
this.queue[this.rear] =value
returntrue
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
func (this*MyCircularQueue) DeQueue() bool {
ifthis.IsEmpty() {
returnfalse
}
ifthis.rear==this.front {
this.rear=-1
this.front=-1
} else {
this.front= (this.front+1) %this.size
}
returntrue
}
/** Get the front item from the queue. */
func (this*MyCircularQueue) Front() int {
ifthis.IsEmpty() {
return-1
}
returnthis.queue[this.front]
}
/** Get the last item from the queue. */
func (this*MyCircularQueue) Rear() int {
ifthis.IsEmpty() {
return-1
}
returnthis.queue[this.rear]
}
/** Checks whether the circular queue is empty or not. */
func (this*MyCircularQueue) IsEmpty() bool {
ifthis.front==-1&&this.rear==-1 {
returntrue
}
returnfalse
}
/** Checks whether the circular queue is full or not. */
func (this*MyCircularQueue) IsFull() bool {
ifthis.front== (this.rear+1)%this.size {
returntrue
}
returnfalse
}