數據結構-隊列操作-用數組實現隊列基本操作

原文鏈接:https://www.goroutine.me/2019/06/13/data-structure-queue-based-on-array-01.html

數據結構中的隊列基本操作,我這裏是也是爲了學習記錄我自己的書寫的代碼過程.其中包含取隊列的新建,新增元素,刪除元素,取指定索引值,向元素尾部追加元素 等等!

1、 場景

1.1、 中文描述

數據結構中的隊列基本操作,我這裏是也是爲了學習記錄我自己的書寫的代碼過程.其中包含取隊列的新建,新增元素,刪除元素,取指定索引值,向元素尾部追加元素 等等!

2、 代碼示例

2.1、 定義一個隊列數據結構

//定義一個隊列數據結構
type ArrayQueue struct {
	q        []interface{} //值
	capacity int           //容量
	head     int           //頭節點
	tail     int           //尾部節點
}

2.2、 新建一個數組隊列

//新建一個數組隊列
func NewArrayQueue(n int) *ArrayQueue {
	return &ArrayQueue{make([]interface{}, n), n, 0, 0}
}

2.3、 檢查隊列是否還可以追加元素 可以追加就加在隊列上 返回狀態

//檢查隊列是否還可以追加元素 可以追加就加在隊列上 返回狀態
func (this *ArrayQueue) EnQueue(v interface{}) bool {
	//檢查隊列長度是否等於tail節點
	if this.capacity == this.tail {
		return false
	}
	this.q[this.tail] = v
	this.tail++
	return true
}

2.4、 取出頭節點數據 並刪除

//取出頭節點數據 並刪除
func (this *ArrayQueue) DeQueue() interface{} {
	//檢查對了是否有數據
	if this.head == this.tail {
		return nil
	}
	v := this.q[this.head]
	//頭節點後移
	this.head++
	return v
}

2.5、 輸出隊列數據

//輸出隊列數據
func (this *ArrayQueue) String() string {
	//檢查隊列是否有數據
	if this.head == this.tail {
		return "Queue is empty"
	}
	result := "head"
	for i := this.head; i <= this.tail-1; i++ {
		result += fmt.Sprintf("<-%v", this.q[i])
	}
	result += "<-tail"
	return result
}

3、 測試源碼

測試方法我上面都追加有測試的命令.可以測試使用

//測試EnQueue 方法
//go test -v -run TestArrayQueue_EnQueue -o QueueBaseOnArray_test.go
func TestArrayQueue_EnQueue(t *testing.T) {
	q := NewArrayQueue(10)
	q.EnQueue(1)
	q.EnQueue(2)
	q.EnQueue(3)
	t.Log(q.String())

}

//測試DeQueue 方法
//go test -v -run TestArrayQueue_DeQueue -o QueueBaseOnArray_test.go
func TestArrayQueue_DeQueue(t *testing.T) {
	q := NewArrayQueue(10)
	q.EnQueue(1)
	q.EnQueue(2)
	q.EnQueue(3)
	//清除元素
	t.Log(q.String())
	q.DeQueue()
	t.Log(q.String())

}

4、 源碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章