Go(单链表)实现简单Stack

//to implement a stack

package main

import (
	"fmt"
	"os"
)

type Stack struct {
	data  interface{}
	next *Stack
}

//inition
func (s *Stack) InitStack() {

	s.next = nil
	s.data = 0
}

//isEmpty
func (s Stack) IsEmpty() bool {
	if s.next == nil {
		return true
	} else {
		return false
	}
}

//push
func (s *Stack) Push(value interface{}){
	s1 := new(Stack)
	//if s1==nil{
	//	fmt.Println("Pushing is failure!")
	//	os.Exit(1)
	//	}
	s1.next = s.next
	s.next = s1
	s1.data = value
	//fmt.Println(s1.data)
}

//poooooooooop
func (s *Stack) Pop() interface{} {
	if s.IsEmpty() {
		fmt.Println("Pop is failure!")
		os.Exit(1)
	}
	temp := s.next
	temp.data = s.next.data
	s.next = temp.next
	fmt.Printf("the pop item value %v\n",temp.data)
	return temp.data
}

//get length
func (s Stack) Len() int {
	i := 0
	temp := s.next
	for x := 1; x > 0; x++ {
		if temp != nil {
			i++
			temp = temp.next
		} else {
			return i
		}
	}
	return i
}

//get pop item
func (s *Stack) GetTop() interface{} {
	if s.IsEmpty() {
		fmt.Println("func:GetTop is failure!")
		os.Exit(1)
	}
	data := s.next.data
	return data
}

//traverse all
func (s Stack) Traverse() {
	temp := s.next
	fmt.Println(temp)
	for i := 0; i < s.Len(); i++ {
		fmt.Printf("Traverse all item [%d] : %v\n", i, temp.data)
		temp = temp.next
	}
}

func main() {
	var s = new(Stack)
	s.InitStack()
	fmt.Println("s is " ,s)
	fmt.Printf("length of Stack is %d\n", s.Len())
	s.Push('a')
	s.Push("lsdfj")
	s.Push(2)
	s.Push(3.13)
	fmt.Println("s is ",s)
	fmt.Printf("length of Stack is %d\n", s.Len())

	s.Traverse()

	fmt.Printf(" Stack-top item is %v\n", s.GetTop())

	fmt.Println(s.Pop())

	s.Traverse()

}

猜你喜欢

转载自my.oschina.net/u/3641281/blog/1613223
今日推荐