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.
转载出处:http://blog.csdn.net/ljiabin/article/details/40982153
class Stack<E> extends Vector<E>
Vector类也是基于数组实现的队列,代码与ArrayList非常相似,只不过在可能发生线程安全的方法上加上了Synchorized关键字,使得其执行的效率相比ArrayList就低了。由于Vector是通过数组实现的,这就意味着,Stack也是通过数组实现的。Vector类可以实现可增长的对象数组。与数组一样,它包含可以使用整数索引进行访问的组件。但是,Vector 的大小可以根据需要增大或缩小,以适应创建 Vector 后进行添加或移除项的操作。
【用Java内置的栈实现】
class MinStack {
private Stack<Integer> stack=new Stack<Integer>(); //class Stack<E> extends Vector<E>
private Stack<Integer> minStack=new Stack<Integer>();
public void push(int x) {
if(minStack.isEmpty() || x<=minStack.peek())
minStack.push(x);
stack.push(x);
}
public void pop() {
if(minStack.peek().equals(stack.peek()))
minStack.pop();
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
private Stack<Integer> stack=new Stack<Integer>(); //class Stack<E> extends Vector<E>
private Stack<Integer> minStack=new Stack<Integer>();
public void push(int x) {
if(minStack.isEmpty() || x<=minStack.peek())
minStack.push(x);
stack.push(x);
}
public void pop() {
if(minStack.peek().equals(stack.peek()))
minStack.pop();
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
【不用内置栈的实现】感觉leetcode测试集还有其他设置的不太完整缜密,但是大体思路对就好了
- class MinStack {
- Node top = null;
- public void push(int x) {
- if (top == null) {
- top = new Node(x);
- top.min = x;
- } else {
- Node temp = new Node(x);
- temp.next = top;
- top = temp;
- top.min = Math.min(top.next.min, x);
- }
- }
- public void pop() {
- top = top.next;
- }
- public int top() {
- return top.val;
- }
- public int getMin() {
- return top.min;
- }
- }
- class Node { //自定义了一个Node class
- int val;
- int min;
- Node next;
- public Node(int val) {
- this.val = val;
- }
- }