［算法］求栈中最小元素
2016-05-09 09:18:09         来源：陶程的博客

``````package 求栈中最小元素;
/**
* 用链表方式实现栈
* @author dream
*
* @param
*/
public class MyStack {

Node top = null;

public boolean isEmpty(){
}

public void push(E data){
Node newNode = new Node(data);
newNode.next = top;
top = newNode;
}

public E pop(){
if(isEmpty()){
return null;
}
E data = top.data;
top = top.next;
return data;
}

public E peek(){
if(isEmpty()){
return null;
}
}
}
``````
``````package 求栈中最小元素;

public class Node {

Node next = null;
E data;
public Node(E data){
this.data = data;
}
}
``````
``````package 求栈中最小元素;

import javax.xml.crypto.dsig.keyinfo.RetrievalMethod;

public class MyStack1 {

MyStack elem;
MyStack min;

public MyStack1(){
elem = new MyStack<>();
min = new MyStack<>();
}

public void push(int data){
elem.push(data);
if(min.isEmpty()){
min.push(data);
}else{
if(data < min.peek()){
min.push(data);
}
}
}

public int pop(){
int topData = elem.peek();
elem.pop();
if(topData == min()){
min.pop();
}
}

public int min(){
if(min.isEmpty()){
return Integer.MAX_VALUE;
}else {
return min.peek();
}
}

}
``````