package 数组实现栈;
public class StackArray implements Stack {
public static final int num = 1024;//数组默认容量
public int capacity;//数组实际容量
public Object s[];//对象数组
public int top = -1;//栈顶元素位置
//构建默认容量栈对象
public StackArray() {
this(num);
}
//构建指定容量栈对象
public StackArray(int a) {
capacity = a;
s = new Object[capacity];
}
//获取栈当前容量
public int getSize() {
return(top+1);
}
//判断栈是否为空
public boolean isEmpty() {
return(top<0);
}
//入栈
public void push(Object obj) throws ExceptionStackFull {
if(getSize() == capacity) {
throw new ExceptionStackFull("栈溢出");
}
else {
s[++top] = obj; // ????????????? 想问下top++为什么不行
}
}
//取栈顶元素
public Object top() throws ExceptionStackEmpty {
if(isEmpty()) {
throw new ExceptionStackEmpty("栈空");
}
else {
return s[top];
}
}
//出栈
public Object pop() throws ExceptionStackEmpty {
if(isEmpty()) {
throw new ExceptionStackEmpty("栈空");
}
else {
Object a = s[top];
s[top--] = null; //???????????? 出栈时不是把s[top]赋空值吗 怎么是s[top--]
return a;
}
}
}
我在用这栈来实现倒置时前面只能是++top 和 top-- 否则出现数组越界
倒置的代码如下
package 数组实现栈;
public class daozhi {
public static void main(String[] args) {
Integer b[] = { 1, 2, 3, 4, 5 };
reverse(b);
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
}
// 实现数组倒置
public static Integer[] reverse(Integer a[]) {
StackArray s = new StackArray(a.length);
// Integer n[] = new Integer[a.length];
for (int i = 0; i < a.length; i++) {
s.push(a[i]);
}
for (int i = 0; i < a.length; i++) {
a[i] = (Integer) s.pop();
}
return a;
}
}