mirror of
https://git.adityakumar.xyz/data-structures.git
synced 2024-11-21 17:32:53 +00:00
add array stack
This commit is contained in:
parent
a813848eff
commit
280f26762e
1 changed files with 42 additions and 0 deletions
42
stack/AStack.java
Normal file
42
stack/AStack.java
Normal 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; }
|
||||||
|
}
|
Loading…
Reference in a new issue