栈的基本操作规则:先进后出
队列中通常使用两个指针,但栈中由于他“先进后出”的特性,不需要栈底指针
package String0924;
//定义一接口,是子类必须实现的一些方法
public interface MyStack {
//jinZhan
public void add(int data);
//chuZhan
public void delete();
//daYin
public void printArr();
}
package String0924;
public class Queue implements MyStack{
//定义数组的最大长度
private int maxsize;
//定义数组
private int[] arr;
//定义头指针 头指针在栈中没有必要
// private int front;
//定义尾指针
private int end;
//定义计数器,判断栈中元素个数
private int count;
public Queue(int maxsize) {
this.maxsize = maxsize; //获取数组长度
arr = new int[maxsize]; //创建数组
end = 0;
count=0;
}
//jinZhan
@Override
public void add(int data) {
if(count==arr.length) {
System.out.println("你好哇! "+data+",栈已经满啦,你要进栈吗?出个栈试试");
}else {
arr[end] = data;
System.out.println(data+" 进栈成功");
count++;
end++; //end指向的是下一次要存入元素的位置
if(count==arr.length) { //若栈中元素已经满了,输出提示分割线
System.out.println("-------------");
}
}
}
//chuZhan
@Override
public void delete() {
if(count==0) {
System.out.println("Boss,栈已经空啦");
}
else {
System.out.println(arr[end-1]+" 出栈");
end--;
count--;
}
}
//daYin
@Override
public void printArr() {
if(count==0) {
System.out.println("栈已经空啦,无法输出数据。");
}
else {
System.out.println("-------------");
System.out.print("当前栈中元素有 : ");
for (int i = 0; i<count; i++) {
System.out.print(arr[i]+" ");
}
}
}
public static void main(String[] args) {
//创建队列数组
Queue aq = new Queue(5);
//入栈
// aq.add(23);
aq.add(55);
aq.add(66);
aq.add(77);
aq.add(89);
aq.add(90);
//出栈
aq.delete();
aq.delete();
aq.add(40);
aq.add(15);
aq.delete();
aq.delete();
aq.add(89);
aq.add(90);
//打印队列
aq.printArr();
}
}