Java_SequentialStack 顺序栈分享
具体内容的解释都在注释上了
StackInterface接口类
public interface StackInterface<T> {
//在接口处声明方法,在类内进行实现
public void push(int element);//用于表达进栈的方法
public int pop();//用于表达出栈的方法
public boolean isEmpty();//用于判断栈是否为空的方法的方法
}
SequentialStack实现接口
import java.util.Arrays;
public class SequentialStack<T> implements StackInterface<T>{
protected int[] stack;//声明数组
private final static int STACK_SIZE=10;//定义数组最大长度
protected int top;//声明top指针
public SequentialStack(){
stack = new int[STACK_SIZE];//初始化数组
top=-1;//定义top指针指向-1位置
}
public boolean isEmpty(){//用于判断栈是否为空的方法的方法
if (top == -1)//如果top指针指向-1的话
return true;//说明栈空
else
return false;//否则就是栈非空
}
public int pop(){//用于表达出栈的方法
if(isEmpty())//如果栈空就抛出异常
throw new RuntimeException("栈空");
int result = stack[top];//定义一个记录top指针指向元素的变量
top--;//出栈后top向前移动一位
return result;//返回出栈时读取的元素
}
public void push(int a) {//用于表达进栈的方法
top++;//将top指针先向后移动一位
stack[top] = a;//给样本空间的第一个位置赋值
if (top == STACK_SIZE)//如果位置超出空间样本最大值,就抛出异常
throw new RuntimeException("栈满、上溢错误,插入失败\n");
}
public int getTop(){//用于读取当前栈顶元素的方法
if (isEmpty())//如果判断为空,则抛出异常
throw new RuntimeException("栈空");
return stack[top];//返回当前top指向的元素
}
public String getSxz() {//用于得到顺序栈的方法
return (Arrays.toString(stack));//返回这个完整的顺序栈
}
}
class ShiJian{//实践类
public static void main(String[] args) {
int[] sxz = {1,3,5,7,9};//定义我要加入顺序栈的数组
SequentialStack sj = new SequentialStack();//声明对象
//通过for循环进行入栈操作
for (int i =0;i<sxz.length;i++) {
sj.push(sxz[i]);
}
System.out.println("现在的顺序栈是"+sj.getSxz());
//进行两次出栈操作,并且输出顺序栈
System.out.println("进行出栈操作后,top指针指向"+sj.pop());
System.out.println("再次进行出栈操作后,top指针指向"+sj.pop());
System.out.println("此时的顺序栈是"+sj.getSxz());
System.out.println("此时top指针指向的元素是"+sj.getTop());
}
}
运行结果
以上就是本文全部内容,如果它对您有帮助,请您帮我点个赞,这对我真的很重要
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。