Java实现栈:
import java.util.Arrays;
public class Stack<T> {
private Object[] elem;// 使用数组实现
private int top;// 指向栈顶元素的指针
public Stack(int size) {
if (size < 1) {
size = 10;// 若用户输入错误大小,默认大小为10
}
this.elem = new Object[size];
this.top = -1;// 栈中无元素,top为-1
}
// 清空栈中的元素
public void clear() {
Arrays.fill(elem, null);
top = -1;
}
// 检查是否为空栈
public boolean isEmpty() {
return top == -1;
}
// 取栈中元素个数
public int length() {
return top + 1;
}
// 取栈顶元素
@SuppressWarnings("unchecked")
public T top() {
if (!isEmpty()) {
return (T) elem[top];
} else
throw new RuntimeException("栈为空");
}
// 入栈
public boolean push(T t) {
if (top == elem.length - 1) {
throw new RuntimeException("栈已满");
} else {
elem[++top] = t;
return true;
}
}
// 弹出栈顶元素
public boolean pop() {
if (isEmpty()) {
throw new RuntimeException("栈已空");
} else {
elem[top--] = null;
return true;
}
}
// 打印,从栈顶到栈底
public void print() {
for (int i = top; i >= 0; i--) {
System.out.print(elem[i] + " ");
}
System.out.println();
}
//简单测试
public static void main(String[] args) {
Stack<Integer> st = new Stack<Integer>(10);
st.push(1);
st.push(5);
st.print();
System.out.println("栈顶元素:" + st.top());
st.pop();
System.out.println("出栈后栈顶元素:" + st.top());
System.out.println("栈中元素个数为:" + st.length());
st.clear();
for (int i = 0; i < 5; i++) {
System.out.print(i + ": " + st.elem[i] + " ");
}
}
}