Skip to content

Instantly share code, notes, and snippets.

@devdilson
Last active December 12, 2021 19:34
Show Gist options
  • Save devdilson/29be3a3b7d365c59b52635a327b828e6 to your computer and use it in GitHub Desktop.
Save devdilson/29be3a3b7d365c59b52635a327b828e6 to your computer and use it in GitHub Desktop.
Simple Stack implementation using arrays in Java
package io.nxz.interview.study.stack;
public class CArrayStack<T> {
private int currentSize;
private T[] items;
public CArrayStack(int initialSize) {
this.items = (T[]) new Object[initialSize];
}
public void push(T value) {
if (currentSize == items.length) {
grow();
}
items[currentSize++] = value;
}
public T pop() {
if (currentSize < 1) {
return null;
}
int removeIndex = currentSize - 1;
T value = this.items[removeIndex];
this.items[removeIndex] = null;
currentSize--;
return value;
}
public T peek() {
if (currentSize < 1) {
return null;
}
return this.items[currentSize - 1];
}
private void grow() {
final T[] newArr = (T[]) new Object[currentSize + currentSize / 2];
System.arraycopy(items, 0, newArr, 0, items.length);
this.items = newArr;
}
public boolean isEmpty() {
return currentSize < 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment