leetcode 用棧實現隊列

type MyQueue struct {
     InputStack  []int //輸入棧
    OutputStack []int //輸出棧
}


/** Initialize your data structure here. */
func Constructor() MyQueue {
    queue := MyQueue{[]int{}, []int{}}
    return queue
}


/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int)  {
    //元素加入輸入棧
    this.InputStack = append(this.InputStack, x)
}


/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
    //當輸出棧不爲空的,那就直接取出輸出棧頂元素
    if len(this.OutputStack) != 0 {
        x := this.OutputStack[len(this.OutputStack)-1]
        this.OutputStack = this.OutputStack[:len(this.OutputStack)-1]
        return x
    }
    //如果輸出棧爲空,但是輸入棧不爲空,那就把輸入棧的元素放進輸出棧,並去除棧頂元素
    if len(this.InputStack) != 0 {
        for i := len(this.InputStack); i > 0; i-- {
            this.OutputStack = append(this.OutputStack, this.InputStack[i-1])
            this.InputStack = this.InputStack[:len(this.InputStack)-1]
        }
        x := this.OutputStack[len(this.OutputStack)-1]
        this.OutputStack = this.OutputStack[:len(this.OutputStack)-1]
        return x
    }
    return 0 //兩個棧都是空的
}


/** Get the front element. */
func (this *MyQueue) Peek() int {
    //如果存在輸出棧元素 那就直接輸出棧頂元素
     if len(this.OutputStack) != 0 {
        return this.OutputStack[len(this.OutputStack)-1]
    }
    if len(this.InputStack) != 0 {
        for i := len(this.InputStack); i > 0; i-- {
            this.OutputStack = append(this.OutputStack, this.InputStack[i-1])
            this.InputStack = this.InputStack[:len(this.InputStack)-1]
        }
        return this.OutputStack[len(this.OutputStack)-1]
    }
    return 0
}


/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
      if len(this.InputStack)+len(this.OutputStack) == 0 {
        return true
    }
    return false
}


/**
 * 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();
 */

參考鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章