特性:操作受限的线性表,只允许在一端插入和删除数据,后进先出。
数组或链表确实可以替代栈,但是,特定的数据结构是对特定场景的抽象,而且,数组或链表暴露了太多的操作接口,操作上的确灵活自由,但使用时就比较不可控,自然也就更容易出错。
栈主要包括两个操作,入栈和出栈。
用数组实现的栈叫顺序栈;
用链表实现的栈叫链式栈;
时间复杂度O(1),个别情况下O(n),如自动扩容时,进行完整的数据拷贝。
空间复杂度O(1),入栈和出栈只需要一两个临时变量存储空间。
我们所说的时间复杂度,是除了原来的数据存储空间外,算法运行还需要的额外的存储空间。
动态扩展的栈
只需要底层依赖一个支持动态扩容的数组就可以了。当栈满了之后,我们就申请一个更大的数组,将原来的数据搬移到新数组中。
时间复杂度分析:
栈空间不够时,我们重新申请一个是原来大小两倍的数组;
为了简化分析,假设只有入栈操作没有出栈操作;
定义不涉及内存搬移的入栈操作为 simple-push 操作,时间复杂度O(1)
如果当前栈大小为 K,并且已满,当再有新的数据要入栈时,就需要重新申请 2 倍大小的内存,并且做 K 个数据的搬移操作,然后再入栈。但是,接下来的 K-1 次入栈操作,我们都不需要再重新申请内存和搬移数据,所以这 K-1 次入栈操作都只需要一个 simple-push 操作就可以完成。
这 K 次入栈操作,总共涉及了 K 个数据的搬移,以及 K次 simple-push 操作。将 K 个数据搬移均摊到K 次入栈操作,那每个入栈操作只需要一个数据搬移和一个 simple-push 操作。以此类推,入栈操作的均摊时间复杂度为O(1).
顺序栈实现:
/*
基于数组实现的栈
*/
type ArrayStack struct {
//数据
data []interface{}
//栈顶指针
top int
}
func NewArrayStack() *ArrayStack {
return &ArrayStack{
data: make([]interface{}, 0, 32),
top: -1,
}
}
func (this *ArrayStack) IsEmpty() bool {
if this.top < 0 {
return true
}
return false
}
func (this *ArrayStack) Push(v interface{}) {
if this.top < 0 {
this.top = 0
} else {
this.top += 1
}
if this.top > len(this.data)-1 {
this.data = append(this.data, v)
} else {
this.data[this.top] = v
}
}
func (this *ArrayStack) Pop() interface{} {
if this.IsEmpty() {
return nil
}
v := this.data[this.top]
this.top -= 1
return v
}
func (this *ArrayStack) Top() interface{} {
if this.IsEmpty() {
return nil
}
return this.data[this.top]
}
func (this *ArrayStack) Flush() {
this.top = -1
}
func (this *ArrayStack) Print() {
if this.IsEmpty() {
fmt.Println("empty statck")
} else {
for i := this.top; i >= 0; i-- {
fmt.Println(this.data[i])
}
}
}
链式栈实现:
/*
基于链表实现的栈
*/
type node struct {
next *node
val interface{}
}
type LinkedListStack struct {
//栈顶节点
topNode *node
}
func NewLinkedListStack() *LinkedListStack {
return &LinkedListStack{nil}
}
func (this *LinkedListStack) IsEmpty() bool {
if this.topNode == nil {
return true
}
return false
}
func (this *LinkedListStack) Push(v interface{}) {
this.topNode = &node{next: this.topNode, val: v}
}
func (this *LinkedListStack) Pop() interface{} {
if this.IsEmpty() {
return nil
}
v := this.topNode.val
this.topNode = this.topNode.next
return v
}
func (this *LinkedListStack) Top() interface{} {
if this.IsEmpty() {
return nil
}
return this.topNode.val
}
func (this *LinkedListStack) Flush() {
this.topNode = nil
}
func (this *LinkedListStack) Print() {
if this.IsEmpty() {
fmt.Println("empty stack")
} else {
cur := this.topNode
for nil != cur {
fmt.Println(cur.val)
cur = cur.next
}
}
}
应用:
1.浏览器前进后退;
2.函数调用;
3.表达式求值;
4.括号匹配;