LeetCode中数据结构的相互实现

LeetCode第155题:设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

解析:当push(x),x <= min 时先将min进栈,再将x进栈;这也就是说在栈中的每一个min下面都存有前一个min(就是比当前min小的那个)

代码如下:

class MinStack {

    /** initialize your data structure here. */
    Stack<Integer> stack;
    int min;
    public MinStack() {
        stack = new Stack<>();
        min = Integer.MAX_VALUE;
    }
    
    public void push(int x) {//关键在于入栈,入栈前将当前最小元素的下一个最小元素连续入栈两次,比最小值大的,也入栈,不过此时的min变量还是最小值,并没有改变
        if(x <= min){
            stack.push(min);
            min = x;
        }
        stack.push(x);
    }
    
    public void pop() {//出栈时,将最小元素检索,此时最小元素的下一个元素也是最小值,将其赋值给min,这是入栈时的特性所决定的。
        if(stack.pop() == min){
            min = stack.pop();
        }
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return min;
    }
}

详细的过程分析可参见:https://leetcode-cn.com/problems/min-stack/solution/java-jian-ji-wu-fu-zhu-zhan-by-rabbitzhao-2/

LeetCode第225题:用队列实现栈

解析:由于栈和队列的数据结构不同,因此需要使用双队列来完成这个操作。

代码如下:

class MyStack {
    private Queue<Integer> a;//输入队列
    private Queue<Integer> b;//输出队列

    //新建一个队列
    //Queue<String> queue = new LinkedList<String>();

    /** Initialize your data structure here. */
    public MyStack() {
        a = new LinkedList<>();
        b = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        a.offer(x);
        while(! b.isEmpty())
        a.offer(b.poll());//将b队列中的元素传给a队列  
        Queue temp = a;//交换a,b队列中的元素,使得a队列没有在push()的时候始终为空队列
        a = b;
        b = temp;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return b.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return b.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return b.isEmpty();
    }
}

栈和队列的数据进出的关系详细可以参见:https://leetcode-cn.com/problems/implement-stack-using-queues/solution/yong-dui-lie-shi-xian-zhan-by-leetcode/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值