1. 程式人生 > 其它 >Golang佇列

Golang佇列

程式碼

package queue

import "fmt"

type Queue struct {
	Array    []int
	Head     int
	Rear     int
	Capacity int
}

func NewQueue(capacity int) *Queue {
	return &Queue{
		Head:     -1,
		Rear:     -1,
		Capacity: capacity,
	}
}

// 判斷佇列是否為空
func (this *Queue) IsEmpty() bool {
	return this.Head == -1
}

// 判斷佇列是否已滿
func (this *Queue) IsFull() bool {
	return (this.Rear + 1) % this.Capacity == this.Head
}

// 獲取佇列長度
func (this *Queue) GetQueueSize() int {
	if this.Head == -1 {
		return 0
	}
	return (this.Rear + 1 - this.Head + this.Capacity) % this.Capacity
}

// 從尾部入佇列
func (this *Queue) EnQueue(data int) {
	if this.IsFull() {
		fmt.Println("佇列已滿")
	} else {
		this.Rear = (this.Rear + 1) % this.Capacity
		this.Array[this.Rear] = data
		if this.Head == -1 {
			this.Head = this.Rear
		}
	}
}

// 從頭部取資料
func (this *Queue) DeQueue() int {
	var data int
	if this.IsEmpty() {
		fmt.Println("佇列為空")
		return -1
	} else {
		data = this.Array[this.Head]
		if this.Head == this.Rear {
			this.Head = -1
			this.Rear = -1
		} else {
			this.Head = (this.Head + 1) % this.Capacity
		}
		return data
	}
}