1.使用数组实现栈
public class ArrayStack {
private String[] items;
private int count;
public ArrayStack() {
items = new String[5];
count = 0;
}
public void push(String item) {
if(count>=items.length) {
System.out.println("stack is full");
}else {
items[count] = item;
count++;
}
}
public String pop() {
String data = null;
if(count==0) {
System.out.println("stack is null");
}else {
data = items[count-1];
count--;
}
return data;
}
public void display() {
System.out.print("[");
for(int i=0;i<count;i++) {
System.out.print(items[i]+" ");
}
System.out.print("]");
System.out.println();
}
}
2.使用
public class TestArrayStack {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack();
stack.display();
stack.pop();
stack.push("aa");
stack.display();
stack.push("bb");
stack.push("cc");
stack.push("dd");
stack.push("ee");
stack.display();
stack.push("ff");
System.out.println(stack.pop());
System.out.println(stack.pop());
stack.display();
}
}