package Demo24;
import java.util.Stack;
public class StackTest {
private int[] date = new int[10];
private int index;
public boolean push(int d) {//放入元素入栈
if(index < date.length) {
date[index] = d;
index++;
return true;
}//如果该位置大于栈的大小,说明栈已经满了
System.out.println("栈满了");
return false;
}
public int pop() {//出栈
int temp = Integer.MAX_VALUE;
if(index >= 0) {//如果栈内还有元素,直接出栈即可
index--;
temp = date[index];
} else {//栈内没元素,说明栈空了
System.out.println("栈已经空了");
}
return temp;
}
public void print() {//打印栈内元素
for(int i = 0; i < index; i++) {
System.out.print(date[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
StackTest st = new StackTest();
st.push(1);
st.push(2);
st.push(3);
st.push(14);
st.push(5);
st.push(6);
st.push(7);
st.push(8);
st.push(89);
st.print();
System.out.println(st.pop());
System.out.println(st.pop());
System.out.println(st.pop());
System.out.println(st.pop());
st.print();
System.out.println(st.pop());
System.out.println(st.pop());
System.out.println(st.pop());
System.out.println(st.pop());
System.out.println(st.pop());
}
}
用数组来实现堆栈
最新推荐文章于 2023-12-02 09:03:54 发布