队列、栈转化

[TOC]

232. 用栈实现队列

用队列实现栈

package main
import "fmt"

// func main() {
//  obj := Constructor()
//  obj.Push(1)
//  obj.Push(3)
//  obj.Push(2)
//  param_2 := obj.Pop()
//  param_3 := obj.Top()
//  param_4 := obj.Empty()

//  fmt.Println(param_2)
//  fmt.Println(param_3)
//  fmt.Println(param_4)
// }

type MyStack struct {
    element []int
}

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

/** Push element x onto stack. */
func (this *MyStack) Push(x int) {
    if this != nil {
        this.element = append(this.element, x)
    }
}

/** Removes the element on top of the stack and returns that element. */
func (this *MyStack) Pop() int {
    if this != nil {
        if len(this.element) != 0 {
            temp := this.element[len(this.element)-1]
            this.element = this.element[:len(this.element)-1]
            return temp
        }
    }
    return -1
}

/** Get the top element. */
func (this *MyStack) Top() int {
    if this != nil {
        if len(this.element) != 0 {
            return this.element[len(this.element)-1]
        }
    }
    return -1
}

/** Returns whether the stack is empty. */
func (this *MyStack) Empty() bool {
    if len(this.element) == 0 {
        return true
    }
    return false

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容