622.design-circular-queue.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. type MyCircularQueue struct {
  2. queue []int
  3. size int
  4. length int
  5. beg int
  6. end int
  7. }
  8. /** Initialize your data structure here. Set the size of the queue to be k. */
  9. func Constructor(k int) (queue MyCircularQueue) {
  10. queue.queue = make([]int, k)
  11. queue.size = k
  12. return
  13. }
  14. /** Insert an element into the circular queue. Return true if the operation is successful. */
  15. func (this *MyCircularQueue) EnQueue(value int) bool {
  16. if this.IsFull() {
  17. return false
  18. }
  19. this.queue[this.end] = value
  20. this.end = (this.end + 1) % this.size
  21. this.length++
  22. return true
  23. }
  24. /** Delete an element from the circular queue. Return true if the operation is successful. */
  25. func (this *MyCircularQueue) DeQueue() bool {
  26. if this.IsEmpty() {
  27. return false
  28. }
  29. this.beg = (this.beg + 1) % this.size
  30. this.length--
  31. return true
  32. }
  33. /** Get the front item from the queue. */
  34. func (this *MyCircularQueue) Front() int {
  35. if this.IsEmpty() {
  36. return -1
  37. }
  38. return this.queue[this.beg]
  39. }
  40. /** Get the last item from the queue. */
  41. func (this *MyCircularQueue) Rear() int {
  42. if this.IsEmpty() {
  43. return -1
  44. }
  45. return this.queue[(this.end+this.size-1)%this.size]
  46. }
  47. /** Checks whether the circular queue is empty or not. */
  48. func (this *MyCircularQueue) IsEmpty() bool {
  49. return this.length == 0
  50. }
  51. /** Checks whether the circular queue is full or not. */
  52. func (this *MyCircularQueue) IsFull() bool {
  53. return this.length == this.size
  54. }
  55. /**
  56. * Your MyCircularQueue object will be instantiated and called as such:
  57. * obj := Constructor(k);
  58. * param_1 := obj.EnQueue(value);
  59. * param_2 := obj.DeQueue();
  60. * param_3 := obj.Front();
  61. * param_4 := obj.Rear();
  62. * param_5 := obj.IsEmpty();
  63. * param_6 := obj.IsFull();
  64. */