개발/CodingTest

LeetCode - Min Stack

Lumasca 2020. 6. 26. 12:53

음..성능이..

class MinStack {
    
    /** initialize your data structure here. */
    class Node{
        int val;
        Node next;
        
        Node(int val){
            this.val = val;
            this.next = null;
        }
    }
    
    Node top = null;
    public MinStack() {
        
    }
    
    public void push(int x) {
        Node node = new Node(x);
        node.next = top;        
        top = node;
    }
    
    public void pop() {
        top = top.next;
    }
    
    public int top() {
        return top.val;        
    }
    
    public int getMin() {
        Node node = top;
        int min = node.val;
        while(node != null){
            if(min > node.val){
                min = node.val;
            }
            node = node.next;
        }
        return min;
    }
}