题目

双队列模拟栈

题解与代码

题目要求的用两个队列实现栈的操作,栈操作无非
pop():
两个队列的话,用第二个队列仅作为中转,将除最后一个元素的所有元素从inQuene移到outQuene,然后将inQuene清空,再将outQuene移回inQuene。
push()
无脑append
代码:

type MyStack struct {
    inQuene  []int
    outQuene []int
}

func Constructor() MyStack {
    return MyStack{
        inQuene:  make([]int, 0),
        outQuene: make([]int, 0),
    }
}

// Push 将元素 x 压入栈顶。
func (this *MyStack) Push(x int) {
    this.inQuene = append(this.inQuene, x)
}

// Pop 移除并返回栈顶元素
func (this *MyStack) Pop() int {
    for i := 0; i < len(this.inQuene)-1; i++ {
        this.outQuene = append(this.outQuene, this.inQuene[i])
    }
    ret := this.inQuene[len(this.inQuene)-1]
    this.inQuene = []int{}
    for i := 0; i < len(this.outQuene); i++ {
        this.inQuene = append(this.inQuene, this.outQuene[i])
    }
    this.outQuene = []int{}
    return ret
}

// Top 返回栈顶元素
func (this *MyStack) Top() int {
    ret := this.inQuene[len(this.inQuene)-1]
    return ret
}

func (this *MyStack) Empty() bool {
    return len(this.inQuene) == 0 && len(this.outQuene) == 0
}

func (this *MyStack) travel() {
    fmt.Println("[*]:", this.inQuene)
}
分类: 算法

站点统计

  • 文章总数:309 篇
  • 分类总数:19 个
  • 标签总数:191 个
  • 运行天数:1009 天
  • 访问总数:128912 人次

浙公网安备33011302000604

辽ICP备20003309号