dengxinyi 6 лет назад
Родитель
Сommit
a928a39711
1 измененных файлов с 95 добавлено и 0 удалено
  1. 95 0
      medium/641.design-circular-deque.go

+ 95 - 0
medium/641.design-circular-deque.go

@@ -0,0 +1,95 @@
+type MyCircularDeque struct {
+	deque  []int
+	size   int
+	length int
+	beg    int
+	end    int
+}
+
+/** Initialize your data structure here. Set the size of the deque to be k. */
+func Constructor(k int) (deque MyCircularDeque) {
+	deque.deque = make([]int, k)
+	deque.size, deque.beg = k, 1
+	return
+}
+
+/** Adds an item at the front of Deque. Return true if the operation is successful. */
+func (this *MyCircularDeque) InsertFront(value int) bool {
+	if this.IsFull() {
+		return false
+	}
+	this.beg = (this.beg + this.size - 1) % this.size
+	this.deque[this.beg] = value
+	this.length++
+	return true
+}
+
+/** Adds an item at the rear of Deque. Return true if the operation is successful. */
+func (this *MyCircularDeque) InsertLast(value int) bool {
+	if this.IsFull() {
+		return false
+	}
+	this.end = (this.end + 1) % this.size
+	this.deque[this.end] = value
+	this.length++
+	return true
+}
+
+/** Deletes an item from the front of Deque. Return true if the operation is successful. */
+func (this *MyCircularDeque) DeleteFront() bool {
+	if this.IsEmpty() {
+		return false
+	}
+	this.beg = (this.beg + 1) % this.size
+	this.length--
+	return true
+}
+
+/** Deletes an item from the rear of Deque. Return true if the operation is successful. */
+func (this *MyCircularDeque) DeleteLast() bool {
+	if this.IsEmpty() {
+		return false
+	}
+	this.end = (this.end + this.size - 1) % this.size
+	this.length--
+	return true
+}
+
+/** Get the front item from the deque. */
+func (this *MyCircularDeque) GetFront() int {
+	if this.IsEmpty() {
+		return -1
+	}
+	return this.deque[this.beg]
+}
+
+/** Get the last item from the deque. */
+func (this *MyCircularDeque) GetRear() int {
+	if this.IsEmpty() {
+		return -1
+	}
+	return this.deque[this.end]
+}
+
+/** Checks whether the circular deque is empty or not. */
+func (this *MyCircularDeque) IsEmpty() bool {
+	return this.length == 0
+}
+
+/** Checks whether the circular deque is full or not. */
+func (this *MyCircularDeque) IsFull() bool {
+	return this.length == this.size
+}
+
+/**
+ * Your MyCircularDeque object will be instantiated and called as such:
+ * obj := Constructor(k);
+ * param_1 := obj.InsertFront(value);
+ * param_2 := obj.InsertLast(value);
+ * param_3 := obj.DeleteFront();
+ * param_4 := obj.DeleteLast();
+ * param_5 := obj.GetFront();
+ * param_6 := obj.GetRear();
+ * param_7 := obj.IsEmpty();
+ * param_8 := obj.IsFull();
+ */