zoukankan      html  css  js  c++  java
  • 数组模拟栈

    数组模拟栈(Stack)

    package main
    
    import (
    	"fmt"
    )
    
    //使用数组模拟stack
    type Stack struct {
    	Max int //表示最大储存个数
    	Maxtop int
    	arr [5]int
    
    }
    func (s *Stack) IsStackFulll()(bool){
    	if s.Maxtop == s.Max - 1 {
    		return  true
    	}
    	return false
    
    }
    
    func (s *Stack) IsStackEmpty()(bool){
    	if s.Maxtop == -1 {
    		return  true
    	}
    	return false
    
    }
    
    func (s *Stack) Push(val int )(err error){
    	if s.IsStackFulll(){
    		fmt.Println("stack full")
    		return fmt.Errorf("IsStackFulll")
    	}
    	//fmt.Println("s.Maxtop",s.Maxtop)
    	s.Maxtop++
    	s.arr[s.Maxtop] = val
    
    	return
    }
    
    func (s *Stack) List()(err error){
    	if s.IsStackEmpty() {
    		fmt.Println("stack empty")
    		return fmt.Errorf("stack empty")
    	}
    	tmp := s.Maxtop
    	for {
    		if tmp == -1 {
    			break
    		}
    
    		fmt.Println(s.arr[tmp])
    		tmp--
    
    	}
    
    	return
    }
    
    func (s *Stack) Pop()(val int,err error){
    	if s.IsStackEmpty() {
    		fmt.Println("stack empty")
    		return 0,fmt.Errorf("stack empty")
    	}
    	val = s.arr[s.Maxtop]
    	s.Maxtop--
    	return
    }
    
    
    
    
    func main() {
    	stack :=&Stack{
    		Max:5,
    		Maxtop:-1,
    	}
    	stack.Push(1)
    	stack.Push(2)
    	stack.Push(3)
    	stack.Push(4)
    	stack.Push(5)
    	stack.Push(5)
    
    	stack.List()
    	fmt.Println("pop")
    	fmt.Println(stack.Pop())
    	fmt.Println(stack.Pop())
    	fmt.Println(stack.Pop())
    	fmt.Println(stack.Pop())
    
    }
    
    
  • 相关阅读:
    Oracle数据库学习(四)
    近期整理
    2020/5/29
    2020/5/26
    2020/5/25
    2020/5/22
    2020/5/16
    2020/5/15
    2020/5/14
    2020/5/13
  • 原文地址:https://www.cnblogs.com/egrep/p/11886378.html
Copyright © 2011-2022 走看看