package stack;
public class ArrayStack implements Stack {
private T[] items; // æ°ç»
private int top; // æ ä¸å
ç´ ç个æ°ï¼æè
è¯´æ¯æ é¡¶æéï¼
private int capacity; // æ ç容é
public ArrayStack(int capacity) {
this.capacity = capacity;
this.items = (T[]) new Object[capacity];
this.top = 0;
}
// T(N)=O(1)
@Override
public boolean push(T item) {
// æ°ç»ç©ºé´ä¸è¶³ï¼æ æ³push
if (top == capacity) {
return false;
}
// size为å¾
pushçä½ç½®
items[top] = item;
top++;
return true;
}
// T(N)=O(1)
@Override
public T pop() {
// æ°ç»ä¸ºç©ºï¼æ æ³pop
if (top == 0) {
return null;
}
T item = items[top -1];
top--;
return item;
}
// T(N)=O(1)
@Override
public T peek() {
if (top == 0) {
return null;
}
return items[top -1];
}
public static void main(String[] args) {
ArrayStack stack = new ArrayStack<>(4);
stack.push("A");
stack.push("B");
stack.push("C");
stack.push("D");
System.out.println(stack.peek());
stack.pop();
System.out.println(stack.peek());
stack.pop();
stack.pop();
stack.pop();
stack.pop();
System.out.println(stack.peek());
}
}