接口
public interface Stack {
/*** 入栈
*
* @param o
* @return
*/
public boolean push(Object o);
/**
* 长度
*
* @return
*/
public long getSize();
/**
* 出栈
*/
public Object pop();
/**
* 是否为空栈
*
* @return
*/
public boolean isEmpty();
}
实现 :
public class StackImpl implements Stack{
private Note root;
private long size;
public long getSize() {
return size;
}
public boolean isEmpty() {
return size == 0l;
}
public boolean push(Object o) {
if (!validate(o))
throw new NullPointerException("the element can't be null");
Note note = new Note(o);
if (null != root) {
note.last = root;
root = note;
} else {
root = note;
}
size++;
return true;
}
private boolean validate(Object o) {
if (null == o)
return false;
return true;
}
public Object pop() {
if(null!=root){
try{
return root.value;
}finally{
root = root.last;
size--;
}
}
return null;
}
private class Note {
private Note last;
private Object value;
private Note(Object o) {
this.value = o;
}
}
}