题目详见 B站 AV93347594 P88
大意为使用数组实现栈功能, 包括初始化栈、压栈、弹栈
实现代码
public class StackSim {
Object[] ss;
//int oLength;
private int index = 0;
public StackSim() {
}
public StackSim(int n) {
ss = new Object[n];
//oLength = ss.length;
}
public void push(Object o) {
if (index == ss.length) {
System.out.println("栈已满");
return;
}
ss[index] = o;
index += 1;
}
public void pop() {
if (index == 0) {
System.out.println("栈已空");
return;
}
ss[index-1] = null;
index -= 1;
}
}
主要耗时花在了下标相关的逻辑处理
我是把下标默认设为 0 , 那么每次 压栈/弹栈 针对的都是当前栈帧, 动作执行先判断是否满足操作条件, 执行完成后对下标再进行移动操作
老杜在 P93 会给出他的答案, 他将下标默认设为 -1 , 压栈时则是 先移动下标, 再压入对象( 当然也可以像解答中所述写成一句, 使用 ++index )
完成后可以用测试程序来看下效果
public class Test {
public static void main(String[] args) {
StackSim s = new StackSim(3);
s.push("One");
s.push("Two");
s.push(new Integer(9));
System.out.println(s.ss[2]);
s.push(new String("good"));
System.out.println(s.ss[2]);
s.pop();
System.out.println(s.ss[s.ss.length-1]);
s.pop();
System.out.println(s.ss[s.ss.length-1]);
s.pop();
System.out.println(s.ss[s.ss.length-1]);
s.pop();
System.out.println(s.ss[s.ss.length-1]);
s.pop();
}
}