数据结构-栈操作-用链表实现栈基本操作
生活随笔
收集整理的這篇文章主要介紹了
数据结构-栈操作-用链表实现栈基本操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原文鏈接:https://www.goroutine.me/datastructure/2019/06/11/data-structure-stack-based-on-linkedlist-01.html
數據結構中的棧基本操作,我這里是也是為了學習記錄我自己的書寫的代碼過程.其中包含取棧的新建,新增元素,刪除元素,取指定索引值,向元素尾部追加元素 等等!
1、 場景
1.1、 中文描述
數據結構中的棧基本操作,我這里是也是為了學習記錄我自己的書寫的代碼過程.其中包含取棧的新建,新增元素,刪除元素,取指定索引值,向元素尾部追加元素 等等!
2、 代碼示例
2.1、 基于鏈表使用棧的操作
//使用鏈表實現棧的結構 //定義一個鏈表結構 type node struct {next *nodeval interface{} } //定義一個棧鏈表結構 type LinkedListStack struct {topNode *node }2.2、 創建一個棧
//新建一個鏈表棧 func NewLinkedListStack() *LinkedListStack {return &LinkedListStack{nil} }2.3、 判斷棧是否是一個空棧
//判斷棧是否為空 func (this *LinkedListStack) IsEmpty() bool {if this.topNode == nil {return true}return false }2.4、 向棧添加元素
//向鏈表棧push加入數據 func (this *LinkedListStack) Push(v interface{}) {this.topNode = &node{this.topNode, v} }2.5、 刪除棧元素
//刪除棧頂的元素 并返回棧頂的元素 func (this *LinkedListStack) Pop() interface{} {if this.IsEmpty() {return nil}v := this.topNode.val//刪除元素this.topNode = this.topNode.nextreturn v }2.6、 取的棧頂的元素
//取棧頂表的數據 func (this *LinkedListStack) Top() interface{} {if this.IsEmpty() {return nil}return this.topNode.val }2.7、 清除棧的元素
//清空鏈表棧 func (this *LinkedListStack) Flush() {this.topNode = nil }2.8、 打印出棧的內容
//打印 func (this *LinkedListStack) Print() {if this.IsEmpty() {fmt.Println("stack is empty")} else {cur := this.topNodefor nil != cur {fmt.Println(cur.val)cur = cur.next}} }3、 測試源碼
測試方法我上面都追加有測試的命令.可以測試使用
//測試鏈表棧 //go test -v -run TestNewLinkedListStack -o StackBaseOnLinkedList_test.go func TestNewLinkedListStack(t *testing.T) {s := NewLinkedListStack()s.Print() }//測試空鏈表棧 //go test -v -run TestLinkedListStack_IsEmpty -o StackBaseOnLinkedList_test.go func TestLinkedListStack_IsEmpty(t *testing.T) {s := NewLinkedListStack()t.Log(s.IsEmpty()) }//測試push鏈表棧 //go test -v -run TestLinkedListStack_Push -o StackBaseOnLinkedList_test.go func TestLinkedListStack_Push(t *testing.T) {s := NewLinkedListStack()s.Push(1111)s.Push(222)s.Print() }//測試Pop鏈表棧 //go test -v -run TestLinkedListStack_Pop -o StackBaseOnLinkedList_test.go func TestLinkedListStack_Pop(t *testing.T) {s := NewLinkedListStack()s.Push(1111)s.Push(222)s.Print()t.Log(s.Pop())s.Print() }//測試Top鏈表棧 //go test -v -run TestLinkedListStack_Top -o StackBaseOnLinkedList_test.go func TestLinkedListStack_Top(t *testing.T) {s := NewLinkedListStack()s.Push(1111)s.Push(222)s.Print()t.Log(s.Top()) }//測試Top鏈表棧 //go test -v -run TestLinkedListStack_Flush -o StackBaseOnLinkedList_test.go func TestLinkedListStack_Flush(t *testing.T) {s := NewLinkedListStack()s.Push(1111)s.Push(222)s.Print()s.Flush()s.Print()t.Log(s.IsEmpty()) }4、 源碼
-
點擊查看源碼
-
點擊查看測試源碼
-
喜歡可以star下?
總結
以上是生活随笔為你收集整理的数据结构-栈操作-用链表实现栈基本操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ubuntu kvm 部署安装
- 下一篇: 第17课:RDD案例(join、cogr