Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.

 

class MinStack {
	private Stack<Integer> m_data = new Stack<Integer>();  
    private Stack<Integer> m_min = new Stack<Integer>(); 
    public void push(int x) {
    	m_data.push(x);
    	if (m_min.isEmpty() || x < m_min.peek()) {
    		m_min.push(x);
    	} else {
    		m_min.push(m_min.peek());
    	}
    }

    public void pop() {
       // if (!m_min.isEmpty() && !m_data.isEmpty()) {
        	m_min.pop();
        	m_data.pop();
      //  }
    }

    public int top() {
    	return m_data.peek();
    }

    public int getMin() {
    	return m_min.peek();
    }
}

 

你可能感兴趣的:(stack)