641.design-circular-deque.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. type MyCircularDeque struct {
  2. deque []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 deque to be k. */
  9. func Constructor(k int) (deque MyCircularDeque) {
  10. deque.deque = make([]int, k)
  11. deque.size, deque.beg = k, 1
  12. return
  13. }
  14. /** Adds an item at the front of Deque. Return true if the operation is successful. */
  15. func (this *MyCircularDeque) InsertFront(value int) bool {
  16. if this.IsFull() {
  17. return false
  18. }
  19. this.beg = (this.beg + this.size - 1) % this.size
  20. this.deque[this.beg] = value
  21. this.length++
  22. return true
  23. }
  24. /** Adds an item at the rear of Deque. Return true if the operation is successful. */
  25. func (this *MyCircularDeque) InsertLast(value int) bool {
  26. if this.IsFull() {
  27. return false
  28. }
  29. this.end = (this.end + 1) % this.size
  30. this.deque[this.end] = value
  31. this.length++
  32. return true
  33. }
  34. /** Deletes an item from the front of Deque. Return true if the operation is successful. */
  35. func (this *MyCircularDeque) DeleteFront() bool {
  36. if this.IsEmpty() {
  37. return false
  38. }
  39. this.beg = (this.beg + 1) % this.size
  40. this.length--
  41. return true
  42. }
  43. /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
  44. func (this *MyCircularDeque) DeleteLast() bool {
  45. if this.IsEmpty() {
  46. return false
  47. }
  48. this.end = (this.end + this.size - 1) % this.size
  49. this.length--
  50. return true
  51. }
  52. /** Get the front item from the deque. */
  53. func (this *MyCircularDeque) GetFront() int {
  54. if this.IsEmpty() {
  55. return -1
  56. }
  57. return this.deque[this.beg]
  58. }
  59. /** Get the last item from the deque. */
  60. func (this *MyCircularDeque) GetRear() int {
  61. if this.IsEmpty() {
  62. return -1
  63. }
  64. return this.deque[this.end]
  65. }
  66. /** Checks whether the circular deque is empty or not. */
  67. func (this *MyCircularDeque) IsEmpty() bool {
  68. return this.length == 0
  69. }
  70. /** Checks whether the circular deque is full or not. */
  71. func (this *MyCircularDeque) IsFull() bool {
  72. return this.length == this.size
  73. }
  74. /**
  75. * Your MyCircularDeque object will be instantiated and called as such:
  76. * obj := Constructor(k);
  77. * param_1 := obj.InsertFront(value);
  78. * param_2 := obj.InsertLast(value);
  79. * param_3 := obj.DeleteFront();
  80. * param_4 := obj.DeleteLast();
  81. * param_5 := obj.GetFront();
  82. * param_6 := obj.GetRear();
  83. * param_7 := obj.IsEmpty();
  84. * param_8 := obj.IsFull();
  85. */