Go數據結構之棧 stack

package main

import (
	//"errors"
	"fmt"
)

type stack struct {
	size int // 棧容量
	top  int // 棧頂
	data []interface{}  // 數據
}

const stackSize = 15
var stackData = make([]interface{}, stackSize)

// 初始化棧
func initStack() stack {
	s := stack{
		size: stackSize,
		top: -1,
		data: stackData,
	}
	return s
}

func (this *stack) Empty() bool {
	// 判斷棧是否爲空
	return this.top == -1
}

func (this *stack) IsFull() bool {
	// 判斷棧是否已滿
	return this.top == this.size - 1
}

func (this *stack) Push(val interface{}) bool {
	// 入棧
	if this.IsFull() {
		fmt.Println("棧已滿")
		//return errors.New("Stack isFull")
		return false
	}
	this.top += 1 // 棧頂加1
	//fmt.Println(val.(string))
	this.data[this.top] = val  // 將當前元素放在棧頂
	return true
}

func (this *stack) Pop() interface{}{
	if this.Empty(){
		fmt.Println("棧是空的")
		return nil
	}
	popIndex := this.top
	this.top--
	return this.data[popIndex]
}

func (this *stack) Travel() {
	if this.Empty(){
		fmt.Println("棧爲空")
		return
	}
	for i:=0;i<=this.top;i++{
		fmt.Printf("%v  ", this.data[i])
	}
}

func (this *stack) Length() int {
	return this.top + 1
}

func (this *stack) Clear() {
	this.top = -1
}

func main() {
	s := initStack()
	...
}

 

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