两栈共享空间 也就是 一种两个相同数据类型的栈的空间 互相共享。声明一个[20]int 声明一个数组,两个栈一起使用这一个数组
const STACK_MAX_SIZE int = 10
type ElementType int
type DoubleStack struct {
Data [2*STACK_MAX_SIZE]ElementType
top1 int
top2 int
}
top1 代表 栈一当前栈顶元素位置 初始值为-1. top2 代表 栈二当前栈顶元素位置 初始值为 2*STACK_MAX_SIZE
func (this *DoubleStack) Init() {
this.top1 = -1
this.top2 = 2*HEAP_MAX_SIZE
}
在Push 数据时指定stackNumber(所要存放数据的栈) 比如想要存放100到 栈一中 stackNumber 应该为1这是top1 ++, 然后赋值。如果要存放到栈二中则 stackNumber 应该为2, 然后 top2 -- (注意这里是减减, 因为栈2 是以数组的末端作为栈2的栈底的)
func (this *DoubleStack) Push(data ElementType, stackNumber int) {
if this.top1+1 == this.top2 {
panic("out of the stack")
}
if stackNumber == 1 {
this.top1++
this.Data[this.top1] = data
} else if stackNumber == 2 {
this.top2--
this.Data[this.top2] = data
} else {
panic("The stackNumber must be 1 or 2.")
}
}
Pop时 也是通过stackNumber指定要弹出哪一个栈的数据。
func (this *DoubleStack) Pop(stackNumber int) ElementType {
if stackNumber == 1 {
if this.top1 < 0 {
panic("The stack is empty.")
}
data := this.Data[this.top1]
this.top1--
return data
} else if stackNumber == 2 {
if this.top2 >= 2*HEAP_MAX_SIZE {
panic("The stack is empty")
}
data := this.Data[this.top2]
this.top2++
return data
} else {
panic("The stackNumber must be 1 or 2.")
}
}
这中数据结构的应用场景比较少。
下面的可运行的示例代码
package main
import (
"fmt"
)
const HEAP_MAX_SIZE int = 10
type ElementType int
type DoubleStack struct {
Data [2*HEAP_MAX_SIZE]ElementType
top1 int
top2 int
}
func (this *DoubleStack) Init() {
this.top1 = -1
this.top2 = 2*HEAP_MAX_SIZE
}
func (this *DoubleStack) Push(data ElementType, stackNumber int) {
if this.top1+1 == this.top2 {
panic("out of the stack")
}
if stackNumber == 1 {
this.top1++
this.Data[this.top1] = data
} else if stackNumber == 2 {
this.top2--
this.Data[this.top2] = data
} else {
panic("The stackNumber must be 1 or 2.")
}
}
func (this *DoubleStack) Pop(stackNumber int) ElementType {
if stackNumber == 1 {
if this.top1 < 0 {
panic("The stack is empty.")
}
data := this.Data[this.top1]
this.top1--
return data
} else if stackNumber == 2 {
if this.top2 >= 2*HEAP_MAX_SIZE {
panic("The stack is empty")
}
data := this.Data[this.top2]
this.top2++
return data
} else {
panic("The stackNumber must be 1 or 2.")
}
}
func main() {
var doubleStack *DoubleStack = new(DoubleStack)
doubleStack.Init()
for i := 1 ; i <= 15; i++ {
doubleStack.Push(ElementType(i), 1)
}
fmt.Println(doubleStack.Data)
for i := 1 ; i <= 5; i++ {
doubleStack.Push(ElementType(i), 2)
}
fmt.Println(doubleStack.Data)
doubleStack.Pop(1)
doubleStack.Push(ElementType(30), 2)
fmt.Println(doubleStack.top1)
fmt.Println(doubleStack.Data)
}