栈数据结构
/*栈数据结构,该栈可以存贮任何类型的引用*/
public class MyStack {
// Object类型的数组
Object[] objects;
// 栈帧,永远指向栈顶部元素
int index = -1; // 初始化为-1,表示栈中没有元素
// 构造方法
public MyStack() {
// 默认初始化容量为10
objects = new Object[10];
}
public MyStack(int n) {
// 自定义初始化容量
objects = new Object[n];
}
// 压栈
public void push(Object obj) {
if (index >= objects.length - 1) {
System.out.println("压栈失败,栈已满");
return;
}
objects[++index] = obj;
System.out.println("压栈成功");
}
// 弹栈
public Object pop() {
if (index < 0) {
System.out.println("弹栈失败,栈已空");
return null;
}
System.out.println("弹栈成功");
return objects[index--];
}
// set and get
public void setObjects(Object[] objects){
this.objects = objects;
}
public Object[] getObjects() {
return objects;
}
public void setIndex(int index) {
this.index = index;
}
public int getIndex() {
return index;
}
}
测试程序
/*测试程序*/
public class Test {
public static void main(String[] args) {
// 创建一个栈,手动初始化为3
MyStack ms = new MyStact(3);
// 压栈
ms.push(new String("Hello"));
ms.push(new Double(3.14));
ms.push(new Character('中'));
ms.push(new Integer(100));
System.out.println();
// 弹栈
Object o1 = ms.pop();
// 输出
System.out.println(o1);
// 弹栈
Object o2 = ms.pop();
// 输出
System.out.println(o1);
// 弹栈
Object o3 = ms.pop();
// 输出
System.out.println(o1);
// 弹栈
Object o4 = ms.pop();
// 输出
System.out.println(o1);
}
}
运行结果
压栈成功
压栈成功
压栈成功
压栈失败,栈已满
弹栈成功
中
弹栈成功
3.14
弹栈成功
Hello
弹栈失败,栈已空
null