-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.go
116 lines (100 loc) · 2.38 KB
/
solution.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
package main
import "fmt"
// MyCircularQueue is a circular queue
type MyCircularQueue struct {
elements []int
capacity int
front int
rear int
}
// Constructor initializes the data structure. Set the size of the queue to be k.
func Constructor(k int) MyCircularQueue {
cq := MyCircularQueue{capacity: k, front: 0, rear: 0}
cq.elements = make([]int, cq.capacity)
cq.front = -1
cq.rear = -1
return cq
}
// EnQueue inserts an element into the circular queue. Return true if the operation is successful.
func (cq *MyCircularQueue) EnQueue(value int) bool {
if cq.IsFull() {
return false
}
if cq.IsEmpty() {
cq.front = 0
}
cq.rear = (cq.rear + 1) % cq.capacity
cq.elements[cq.rear] = value
return true
}
// DeQueue deletes an element from the circular queue. Return true if the operation is successful.
func (cq *MyCircularQueue) DeQueue() bool {
if cq.IsEmpty() {
return false
}
if cq.front == cq.rear {
cq.front = -1
cq.rear = -1
return true
}
cq.front = (cq.front + 1) % cq.capacity
return true
}
// Front gets the front item from the queue.
func (cq *MyCircularQueue) Front() int {
if cq.IsEmpty() {
return -1
}
return cq.elements[cq.front]
}
// Rear gets the last item from the queue.
func (cq *MyCircularQueue) Rear() int {
if cq.IsEmpty() {
return -1
}
return cq.elements[cq.rear]
}
// IsEmpty checks whether the circular queue is empty or not.
func (cq *MyCircularQueue) IsEmpty() bool {
return cq.front == -1
}
// IsFull checks whether the circular queue is full or not.
func (cq *MyCircularQueue) IsFull() bool {
return cq.front == (cq.rear+1)%cq.capacity
}
/**
* Your MyCircularQueue object will be instantiated and called as such:
* obj := Constructor(k);
* param_1 := obj.EnQueue(value);
* param_2 := obj.DeQueue();
* param_3 := obj.Front();
* param_4 := obj.Rear();
* param_5 := obj.IsEmpty();
* param_6 := obj.IsFull();
*/
func main() {
mcq := Constructor(3)
fmt.Println(mcq)
fmt.Println(mcq.rear)
fmt.Println(mcq.IsFull())
mcq.EnQueue(1)
fmt.Println(mcq)
fmt.Println(mcq.rear)
fmt.Println(mcq.IsFull())
mcq.EnQueue(2)
fmt.Println(mcq)
fmt.Println(mcq.rear)
fmt.Println(mcq.IsFull())
mcq.EnQueue(3)
fmt.Println(mcq)
fmt.Println(mcq.rear)
fmt.Println(mcq.IsFull())
mcq.DeQueue()
fmt.Println(mcq)
fmt.Println(mcq.rear)
fmt.Println(mcq.IsFull())
mcq.EnQueue(4)
fmt.Println(mcq)
fmt.Println(mcq.rear)
fmt.Println(mcq.IsFull())
}