add array stack

This commit is contained in:
Aditya 2022-09-12 19:17:05 +05:30
parent a813848eff
commit 280f26762e

42
stack/AStack.java Normal file
View file

@ -0,0 +1,42 @@
/** Array-based stack implementation */
class AStack<E> implements Stack<E> {
private static final int defaultSize = 10;
private int maxSize; // Maximum size of stack
private int top; // Index for top Object
private E[] listArray; // Array holding stack
/** Constructors */
AStack() { this(defaultSize); }
@SuppressWarnings("unchecked") // Generic array allocation
AStack(int size) {
maxSize = size;
top = 0;
listArray = (E[])new Object[size]; // Create listArray
}
/** Reinitialize stack */
public void clear() { top = 0; }
/** Push "it" onto stack */
public void push(E it) {
assert top != maxSize : "Stack is full";
listArray[top++] = it;
}
/** Remove and pop element */
public E pop() {
assert top != 0 : "Stack is empty";
return listArray[--top];
}
/** @return Top element */
public E topValue() {
assert top != 0 : "Stack is empty";
return listArray[top - 1];
}
/** @return Stack size */
public int length() { return top; }
}