-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathArrayToStack.java
61 lines (52 loc) · 1.27 KB
/
ArrayToStack.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package chapter03StacksAndQueues;
import java.util.EmptyStackException;
/**
*
* Problem: Describe how you could use a single array to implement three stacks.
*
*/
public class ArrayToStack {
private static final int NUMBEROFSTACKS = 3;
private int stackCapacity;
private int[] vals;
private int[] sizes;
public ArrayToStack(int stackCapacity) {
this.stackCapacity = stackCapacity;
vals = new int[NUMBEROFSTACKS * stackCapacity];
sizes = new int[NUMBEROFSTACKS];
}
public void push(int stackNum, int num) {
if (isFull(stackNum)) {
return;
}
sizes[stackNum]++;
vals[indexOfTop(stackNum)] = num;
}
public int pop(int stackNum) {
if (isEmpty(stackNum)) {
throw new EmptyStackException();
}
int topIndex = indexOfTop(stackNum);
int val = vals[topIndex];
vals[topIndex] = 0;
sizes[stackNum]--;
return val;
}
public int peek(int stackNum) {
if (isEmpty(stackNum)) {
throw new EmptyStackException();
}
return vals[indexOfTop(stackNum)];
}
public boolean isEmpty(int stackNum) {
return sizes[stackNum] == 0;
}
public boolean isFull(int stackNum) {
return sizes[stackNum] == stackCapacity;
}
private int indexOfTop(int stackNum) {
int offset = stackNum * stackCapacity;
int size = sizes[stackNum];
return offset + size;
}
}