class LinkedStack<T> {
private Node top;
private int size;
/**
* 初始化栈
*/
public LinkedStack() {
top = null;
size = 0;
}
/**
* 判断栈是否为空
*
* @return
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 清空栈元素
*/
public void clear() {
top = null;
size = 0;
}
/**
* 获取栈的大小
*
* @return
*/
public int length() {
return size;
}
/**
* 将一个数据入栈
*
* @param data
* @return
*/
public boolean push(T data) {
Node node = new Node(data);
node.pre = top;
top = node;
size++;
return true;
}
/**
* 将数据出栈,并删除
*
* @return
*/
public T pop() {
if (top != null) {
Node node = top;
top = top.pre;
size--;
return node.data;
}
return null;
}
/**
* 获取栈顶元素,但不删除该栈元素数据
*
* @return
*/
public T peek() {
if (top != null) {
return top.data;
}
return null;
}
/**
* 节点类
*
* @author John
*
*/
private class Node {
Node pre;
T data;
public Node(T data) {
this.data = data;
}
}
}