美文网首页
leetcode232 用栈实现队列 golang

leetcode232 用栈实现队列 golang

作者: lucasgao | 来源:发表于2021-03-05 23:30 被阅读0次

解题思路

使用栈模拟队列,
栈的特性:先进后出
队列特性:先进先出。

所以可以使用2个栈,S1 pop的数据放到S2那么我们就可以保证 S2 pop出的数据是先进先出的。

代码里没有保证空指针出错。

这里自定义了一个stack,因为go里没有栈,所以用数组进行了模拟,并把栈的相关方法暴露出来。

代码

// 因为go 没有栈这样的数据结果,所以先实现一个栈出来。
type Stack struct{
    A []int
}

func (s *Stack) Push(x int){
    s.A = append(s.A,x)
}

func (s *Stack) Pop()int{
    l := s.Size()
    t := s.A[l-1]
    s.A = s.A[:l-1]
    return t
}

func (s *Stack) Top()int{
    l := s.Size()
    t := s.A[l-1]
    return t
}

func (s *Stack)Size() int{
    return len(s.A)
}

func (s *Stack)Empty()bool{
    return s.Size() == 0
}

type MyQueue struct {
    S1,S2 Stack
}


/** Initialize your data structure here. */
func Constructor() MyQueue {
    return MyQueue{}
}


/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int)  {
    this.S1.Push(x)
}


/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
    // 当S2空的时候,需要把S1的数据放到S2中
    if this.S2.Empty(){
        for !this.S1.Empty(){
            t := this.S1.Pop()
            this.S2.Push(t)
        }
    }
    return this.S2.Pop()
}


/** Get the front element. */
func (this *MyQueue) Peek() int {
  // 当S2空的时候,需要把S1的数据放到S2中
    if this.S2.Empty(){
        for !this.S1.Empty(){
            t := this.S1.Pop()
            this.S2.Push(t)
        }
    }
    return this.S2.Top()
}


/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
    return this.S1.Empty() && this.S2.Empty()
}


/**
 * Your MyQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(x);
 * param_2 := obj.Pop();
 * param_3 := obj.Peek();
 * param_4 := obj.Empty();
 */

相关文章

  • Leetcode day2 栈和队列

    Leetcode232、225:栈和队列互相实现,尽管python里面没有栈和队列,用list比较别扭,但是理解逻...

  • leetcode232 用栈实现队列 golang

    解题思路 使用栈模拟队列,栈的特性:先进后出队列特性:先进先出。 所以可以使用2个栈,S1 pop的数据放到S2那...

  • 数据结构——栈和队列

    用数组实现栈和队列 用栈实现队列 用队列实现栈 栈和队列的经典算法题最小间距栈宠物收养所 数组实现栈和队列 用数组...

  • golang 队列和栈的实现

    在 python 中实现队列或者栈非常简单,用list就可以用来做一个简单的栈和队列,如下 那么,在 golang...

  • leecode刷题(26)-- 用栈实现队列

    leecode刷题(26)-- 用栈实现队列 用栈实现队列 使用栈实现队列的下列操作: push(x) -- 将一...

  • C语言第七次作业:链表

    707. 设计链表 空指针 空节点 225. 用队列实现栈 链式存储栈 双队列实现栈 232. 用栈实现队列 链式...

  • 队列之-队列实现栈

    一、队列实现栈核心算法概述 之前已经描述过了用栈实现队列的功能,见栈系列之-实现队列,那么同样队列也可以用来实现栈...

  • 38_两个有趣的问题

    关键词:通过栈实现队列、通过队列实现栈 0. 通过栈实现队列 用栈实现队列等价于用后进先出的特性实现先进先出的特性...

  • 栈&队列

    一、栈&队列总结 栈/队列的应用接雨水验证栈序列滑动窗口的最大值 栈/队列的特殊实现用两个栈实现队列用两个队列实现...

  • 面试题9: 用两个栈实现队列

    9-1 用两个栈实现队列 9-2 用两个队列实现栈

网友评论

      本文标题:leetcode232 用栈实现队列 golang

      本文链接:https://www.haomeiwen.com/subject/qztjqltx.html