Retrieving the Min element in a stack in O(1) Time

后端 未结 3 1032
一生所求
一生所求 2021-02-06 09:33

The reason I\'m asking this question is because I cannot see why the way I think cannot be applied to this particular question

\"How would you design a stack which,

3条回答
  •  生来不讨喜
    2021-02-06 10:01

    Use a linked list to keep track of the minimum value which is gonna be the head.

    Note that linkedlist.app= append ( we put the value in the tail ). linkedlist.pre =prepend ( we put the value as the head of the linkedlist)

    public class Stack {

    int[] elements;
    int top;
    Linkedlists min;
    
    public Stack(int n) {
        elements = new int[n];
        top = 0;
        min = new Linkedlists();
    }
    
    public void realloc(int n) {
        int[] tab = new int[n];
        for (int i = 0; i < top; i++) {
            tab[i] = elements[i];
        }
    
        elements = tab;
    }
    
    public void push(int x) {
        if (top == elements.length) {
            realloc(elements.length * 2);
        }
        if (top == 0) {
            min.pre(x);
        } else if (x < min.head.data) {
            min.pre(x);
        } else {
            min.app(x);
        }
        elements[top++] = x;
    }
    
    public int pop() {
    
        int x = elements[--top];
        if (top == 0) {
    
        }
        if (this.getMin() == x) {
            min.head = min.head.next;
        }
        elements[top] = 0;
        if (4 * top < elements.length) {
            realloc((elements.length + 1) / 2);
        }
    
        return x;
    }
    
    public void display() {
        for (Object x : elements) {
            System.out.print(x + " ");
        }
    
    }
    
    public int getMin() {
        if (top == 0) {
            return 0;
        }
        return this.min.head.data;
    }
    
    public static void main(String[] args) {
        Stack stack = new Stack(4);
        stack.push(2);
        stack.push(3);
        stack.push(1);
        stack.push(4);
        stack.push(5);
        stack.pop();
        stack.pop();
        stack.pop();
        stack.push(1);
        stack.pop();
        stack.pop();
        stack.pop();
        stack.push(2);
        System.out.println(stack.getMin());
        stack.display();
    
    }
    

    }

提交回复
热议问题