题目:定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
思路:和普通栈一样,包含入栈,出栈,只不过在入栈的时候判断并保存最小值,在出栈时重新计算最小值。
ArrayList实现:
public class Solution {
private ArrayList<Integer> list = new ArrayList();
int min = -1;
public void push(int node) {
list.add(node);
if(node<min||min==-1){
min = node;
}
}
public void pop() {
if(list.size()>1){
if(list.get(list.size()-1)==min){
min = list.get(0);
}
list.remove(list.size()-1);
for(int te:list){
if(te<min){
min = te;
}
}
}
}
public int top() {
if(list.size()>1){
int res = list.get(list.size()-1);
return res;
}
return 0;
}
public int min() {
return min;
}
}
链表实现:
public class Solution {
public static class Node{
int val;
Node next;
public Node(int val){this.val = val;}
}
private Node head;
int min = -1;
public void push(int node) {
Node newNo = new Node(node);
newNo.next = head;
head = newNo;
if(min>node||min==-1){
min = node;
}
}
public void pop() {
if(head!=null){
Node temp = head.next;
head.next = null;
if(min == head.val){
if(temp!=null){
min = temp.val;
}
Node no = temp;
while(no!=null){
if(no.val<min){
min = no.val;
}
no = no.next;
}
}
head = temp;
}
}
public int top() {
if(head!=null){
return head.val;
}
return 0;
}
public int min() {
return min;
}
}