Question: Three in One: Describe how you could use a single array to implement three stacks.
My Thought Process:
The first one is from the beginning.
The middle one
The last one is from the end.
Problem: Stack will not have an equal size.
Answer:
Stack 1: [0, n/3]
Stack 2: [n/3, 2n/3]
Stack 3: [2n/3, n]
Implementation:
public class ThreeStackInOne {
private int numberOfStacks = 3;
private int stackCapacity;
private int[] values;
private int[] sizes;
public ThreeStackInOne(int stackSize) {
stackCapacity = stackSize;
values = new int[stackSize * numberOfStacks];
sizes = new int[numberOfStacks];
}
/* Push Values onto stack. */
public void push(int stackNum, int value) throws Exception {
/* Check that we have space for the next element */
if (isFull(stackNum)) {
throw new Exception("Stack is full");
} else {
/* Increment stack pointer and then update top value. */
sizes[stackNum]++;
values[indexOfTop(stackNum)] = value;
}
}
/* Pop Item from top stack*/
public int pop(int stackNum) throws NoSuchElementException {
if (isEmpty(stackNum)){
throw new NoSuchElementException();
}
int value = values[indexOfTop(stackNum)];
values[indexOfTop(stackNum)] = 0;
sizes[stackNum]--;
return value;
}
/* Return if stack is empty. */
public boolean isEmpty(int stackNum) {
return sizes[stackNum] == 0;
}
/* Return if stack is full. */
public boolean isFull(int stackNum) {
return sizes[stackNum] == stackCapacity;
}
/*Return index of the top of the stack. */
private int indexOfTop(int stackNum) {
int offset = stackNum * stackCapacity;
int size = sizes[stackNum];
return offset + size - 1;
}
}
'Algorithms and Data Structures > Coding Practices' 카테고리의 다른 글
CCI 4.3 List of Depths (0) | 2022.06.02 |
---|---|
CCI 4.1 Route Between Nodes (0) | 2022.05.31 |
[LinkedList] CCI 2.1 (0) | 2022.05.20 |
[LeetCode] 36. Valid Sudoku (0) | 2022.05.19 |
[LeetCode] 11 Container With Most Water (0) | 2022.05.18 |