Created
May 28, 2018 09:32
-
-
Save sangcomz/baa578fa7e8fc3a8b512e098c191d8ee to your computer and use it in GitHub Desktop.
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
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