要求和提示
代码段
package 数组与数据结构;
import java.util.Scanner;
//一维数组模拟栈结构
public class Mystack {
// 创建一维数组
// Object可以存放任何数据类型的数据
private Object[] array;
//栈顶,初始值为0
private int index=0;
public Object[] getArray() {
return array;
}
public void setArray(Object[] array) {
this.array = array;
}
//利用构造函数初始化对象
public Mystack( ) {
//默认输入10
System.out.println("输入数组初始化长度:");
Scanner sc= new Scanner(System.in);
int a= sc.nextInt();
this.array=new Object[a];
System.out.println("输入数组初始化成功:");
}
//压栈
public void push(Object obj) {
if(this.index>=this.array.length)
{
System.out.println("栈满,压栈失败");
return ; //结束
}
this.array[index]=obj;
System.out.println("压栈成功!栈顶指向"+this.index);
this.index ++;
}
//出站
public void pop( Object obj)
{
if(this.index<=0)
{
System.out.println("栈空,出栈失败");
return ; //结束
}
this.index --;
System.out.println("出栈成功!栈顶指向"+this.index +"栈元素是"+this.array[index]);
this.array[index]=obj;
}
public static void main(String [] agrs) {
Mystack a= new Mystack();
a.push(new Object());
a.push(new Object());
a.push(new Object());
a.push(new Object());
a.push(new Object());
a.pop(new Object());
a.pop(new Object());
a.pop(new Object());
a.pop(new Object());
a.pop(new Object());
}
上述代码在测试块中可以使用循环的手段持续压栈出栈,友友们可以自己尝试一下