Jianzhi Offer 09 Realize the queue with two stacks (go language realizes the linked list stack)

Original address:

https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/
insert image description here

The idea of ​​solving the problem is that the s1 stack is used to enter the queue. When it is necessary to exit the queue, the elements of the s1 stack are sequentially popped into the s2 stack, and then the s2 stack is popped out of the stack. The special thing about this question is that I think the list in the go language standard library is not particularly easy to use and takes a lot of time, so I implemented the linked list stack by myself. Of course, I chose the linked list stack, and slices can also be used to implement sequential stacks.

type CQueue struct {
    
    
    S1,S2 *Stack
}

type Stack struct{
    
    
    Pre *Stack
    Val int
}

//需要使用两层指针,第一层指针可以改变指针指向的Stack节点的值
//而第二层指针可以改变指针指向的Stack节点
//因为栈需要改变栈顶指针指向最新的元素,所以需要改变指针的指向
//所以使用了双层指针
func Push(s **Stack,val int){
    
    
    n := new(Stack)
    n.Val = val
    n.Pre = *s
    *s = n
}
func Pop(s **Stack)int{
    
    
    res := (*s).Val
    *s = (*s).Pre
    return res
}

func Constructor() CQueue {
    
    
    return CQueue{
    
    }
}


func (this *CQueue) AppendTail(value int)  {
    
    
    Push(&this.S1,value)
}


func (this *CQueue) DeleteHead() int {
    
    
    if this.S2 == nil{
    
    
        if this.S1 == nil{
    
    
            return -1
        }
        for this.S1 !=nil{
    
    
            Push(&this.S2,Pop(&this.S1))
        }
        return Pop(&this.S2)
    }else{
    
    
        return Pop(&this.S2)
    }
}


/**
 * Your CQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.AppendTail(value);
 * param_2 := obj.DeleteHead();
 */

insert image description here
272ms uses the container/list of the standard library

Guess you like

Origin blog.csdn.net/rglkt/article/details/119053576