Skip to content

Instantly share code, notes, and snippets.

@sangcomz
Created May 28, 2018 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sangcomz/baa578fa7e8fc3a8b512e098c191d8ee to your computer and use it in GitHub Desktop.
Save sangcomz/baa578fa7e8fc3a8b512e098c191d8ee to your computer and use it in GitHub Desktop.
public class CircularStack<T> {
private LruCache<Integer, T> valueHistory;
private int bottom;
private int top;
public CircularStack(int maxSize) {
valueHistory = new LruCache<>(maxSize + 1);
bottom = 0;
top = 0;
}
public void push(T value) {
top = (top + 1) % valueHistory.maxSize();
if (top == bottom) {
bottom = (bottom + 1) % valueHistory.maxSize();
System.out.println("Stack is full.");
}
valueHistory.put(top, value);
print();
}
public T pop() {
if (top == bottom) {
System.out.println("Stack is empty.");
return null;
}
T tmp = valueHistory.get(top);
top = (valueHistory.maxSize() + (top - 1)) % valueHistory.maxSize();
print();
return tmp;
}
public void print() {
int curr = bottom;
if (curr == top) {
System.out.println("[empty]");
} else while (curr != top) {
curr = (curr + 1) % valueHistory.maxSize();
System.out.println(String.valueOf(curr) + " " + valueHistory.get(curr) + " ");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment