-
Notifications
You must be signed in to change notification settings - Fork 0
/
IntStack.java
33 lines (33 loc) · 876 Bytes
/
IntStack.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
/**
* Created by Paul on 5/1/2015.
*/
public class IntStack {
private int[] data = new int[2];
private int size;
public int getSize(){
return size;
}
private void doubleSize(){
int[] newData = new int[data.length * 2];
for(int i = 0; i < size; ++i){
newData[i] = data[i];
}
data = newData;
}
private void halfSize(){
int[] newData = new int[data.length / 2];
for(int i = 0; i < size; ++i){
newData[i] = data[i];
}
data = newData;
}
public void push(int item){
if(size == data.length) doubleSize();
data[size++] = item;
}
public int pop(){
if(size == data.length / 4) halfSize();
if(size == 0) throw new IllegalStateException("trying to pop from and empty stack!");
return data[--size];
}
}