数据结构和算法-栈

167 阅读1分钟

定义

栈是一种操作受限的线性表结构,只能在一端插入删除元素,故有先入后出,后入先出的特征,可以用链表或者数组实现。

算法

栈的操作就两个

  • 入栈
  • 出栈

时间和空间复杂度都应该为O(1)

应用场景

任何有先出后出,后入先出需求的场景都可以考虑使用栈,比如

  • 函数调用栈
  • 表达式求值
  • 括号匹配
  • 浏览器的前进后退

实现

使用数组

  • 时间复杂度:O(1)
  • 空间复杂度:O(1)
type Stack struct {
    Elements []int
}

func Constructor() Stack {
    return Stack{[]int{}}
}

func (this *Stack) Pop() int {
    if len(this.Elements) == 0 {
	return -1
    }
    val := this.Elements[len(this.Elements)-1]
    this.Elements = this.Elements[:len(this.Elements)-1]
    return val
}

func (this *Stack) Push(val int) {
    this.Elements = append(this.Elements, val)
}

使用链表(双向)

  • 时间复杂度:O(1)
  • 空间复杂度:O(1)
type Node struct {
    Val int
    Next *Node
    Pre *Node
}

type Stack struct {
    Element *Node
}

func Constructor() Stack {
    return Stack{}
}

func (this *Stack) Pop() int {
    if this.Element != nil {
        val := this.Element.Val
	this.Element = this.Element.Pre
	if this.Element != nil {
            this.Element.Next = nil
	}
        return val
    }
    return -1
}

func (this *Stack) Push(val int) {
    node := &Node{val, nil, nil}
    if this.Element == nil {
	this.Element = node
    } else {
	node.Pre = this.Element
	this.Element.Next = node 
	this.Element = node
    }
}