? ? ? ? 栈只允许访问一个数据项:即最后插入的一个元素。只有移除最后一个元素之后,才能访问倒数第二插入的元素。
public class Stack {
public static void main(String[] args) {
Stack stack = new Stack(10);
//入栈
for (int i = 0; i < 10; i++) {
stack.push(i);
}
//出栈
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
private long data[];
private int top;
private int capacity;
public Stack(int capacity) {
this.capacity = capacity;
data = new long[capacity];
top = -1;
}
//入栈
public void push(long value) {
if (top == capacity - 1) {
System.out.println("Stack is full");
return;
}
data[++top] = value;
}
//出栈
public long pop() {
return data[top--];
}
//查看栈顶元素
public long peek() {
return data[top];
}
//查看栈是否为空
public boolean isEmpty() {
return top == -1;
}
//判断栈是否满
public boolean isFull() {
return top == capacity - 1;
}
}
? ? ? ? 分隔符匹配