Last active
December 12, 2021 19:34
-
-
Save devdilson/29be3a3b7d365c59b52635a327b828e6 to your computer and use it in GitHub Desktop.
Simple Stack implementation using arrays in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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