Stack Using Array
Implementing a stack using an array is straightforward. We maintain a fixed-size array and a variable `top` that points to the index of the top element. The array gives O(1) access but has a fixed capacity.
Array-based stack implementation
public class ArrayStack<T> {
private Object[] arr;
private int top;
private int capacity;
public ArrayStack(int capacity) {
this.capacity = capacity;
arr = new Object[capacity];
top = -1;
}
public void push(T item) {
if (top == capacity - 1) throw new RuntimeException("Stack overflow");
arr[++top] = item;
}
public T pop() {
if (isEmpty()) throw new RuntimeException("Stack underflow");
return (T) arr[top--];
}
public T peek() {
if (isEmpty()) throw new RuntimeException("Stack empty");
return (T) arr[top];
}
public boolean isEmpty() {
return top == -1;
}
public int size() {
return top + 1;
}
}
Two Minute Drill
- Array-based stack uses a fixed-size array and top index.
- push: O(1), pop: O(1), peek: O(1).
- May throw overflow if full, underflow if empty.
- Simple and fast, but capacity is fixed.
Need more clarification?
Drop us an email at career@quipoinfotech.com
