题解 | 包含min函数的栈

包含min函数的栈

https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49

import java.util.*;
import java.util.Stack;

public class Solution {

    Stack<Integer> origin=new Stack<Integer>();
    Stack<Integer> orderStack =new Stack<Integer>();

    Stack<Integer> other =new Stack<Integer>();
    public void push(int node) {
       // origin.push(node);
        if(orderStack.isEmpty()){
            orderStack.push(node);
        }else if(orderStack.peek()<node){
            while(!orderStack.isEmpty()&&orderStack.peek()<node){
                other.push(orderStack.pop());
            }
            orderStack.push(node); 
            while(!other.isEmpty()){
                orderStack.push(other.pop());
            }
        }else if(orderStack.peek()>=node){
            orderStack.push(node); 
        }
        origin.push(node);
    

        System.out.println(origin.peek());
        System.out.println(orderStack.peek());
    }
    
    public void pop() {
        // 我能想到用一个索引 或者借助一个空的栈  空的栈是最简单的 这样的话 删除后 在添加就可以了
        int peek=origin.pop();
         while(orderStack.peek()!=peek){
            other.push(orderStack.pop());
          }
          orderStack.pop();
          while(!other.isEmpty()){
                orderStack.push(other.pop());
          }
    }
    
    public int top() {
        return origin.peek();
    }
    
    public int min() {
        return orderStack.peek();
    }
}

全部评论

相关推荐

政委qqq:这道题在算法竞赛里唯一考的就是高精度,但是只能难住C++这类语言,Python直接a+b秒天秒地
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务