zoukankan      html  css  js  c++  java
  • 数组栈 ArrayStack

    package main
    
    import (
    	"fmt"
    	"strings"
    )
    
    type ArrayStack struct {
    	data []int // 存放数据的位置
    	top  int   // 栈顶指针
    }
    
    /** Initialize your data structure here. */
    func Constructor() *ArrayStack {
    	return &ArrayStack{
    		data: make([]int, 0, 32),
    		top:  -1,
    	}
    }
    
    /** Size  */
    func (this *ArrayStack) Size() int {
    	return this.top + 1
    }
    
    /** Push element x to the back of queue. */
    func (this *ArrayStack) Push(x int) {
    	this.top += 1
    	if this.top > len(this.data)-1 {
    		this.data = append(this.data, x)
    	} else {
    		this.data[this.top] = x
    	}
    }
    
    /** Removes the element from in front of queue and returns that element. */
    func (this *ArrayStack) Pop() int {
    	if this.Empty() {
    		return -1
    	}
    	x := this.data[this.top]
    	this.top -= 1
    	return x
    }
    
    /** Get the front element. */
    func (this *ArrayStack) Peek() int {
    	if this.Empty() {
    		return -1
    	}
    	return this.data[this.top]
    }
    
    /** Returns whether the queue is empty. */
    func (this *ArrayStack) Empty() bool {
    	return this.top == -1
    }
    
    /** String pring string */
    func (this *ArrayStack) String() string {
    	if this.Empty() {
    		return "empty stack"
    	}
    	return strings.Trim(strings.Replace(fmt.Sprint(this.data), " ", ",", -1), "[]")
    }
    
    func main() {
    	obj := Constructor()
    	obj.Push(2)
    	obj.Push(6)
    	obj.Push(8)
    	obj.Push(9)
    
    	fmt.Println(obj)
    	val := obj.Pop()
    	fmt.Println(val)
    	val = obj.Peek()
    	fmt.Println(val)
    	b := obj.Empty()
    	fmt.Println(b)
    }
    
  • 相关阅读:
    CentOS安装sctp协议
    视频编码未来简史
    Linux内核:分析coredump文件
    skb的两个函数pskb_copy和skb_copy
    《Linux内核设计与实现》读书笔记(十二)- 内存管理
    Linux内核学习笔记之seq_file接口创建可读写proc文件
    内核如何签名
    《女士品茶》与统计检验
    K近邻算法
    PCA原理分析
  • 原文地址:https://www.cnblogs.com/warrior/p/13353370.html
Copyright © 2011-2022 走看看