-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.java
68 lines (56 loc) · 1.45 KB
/
Stack.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
62
63
64
65
66
67
68
package com.brian.portfolio.datastructures;
import java.util.Arrays;
public class Stack {
private int size;
private int count;
private int[] items;
public Stack(int size) {
this.size = size;
this.items = new int[size];
}
public void push(int item) {
resizeArray();
items[count++] = item;
}
public int pop() {
if (isEmpty())
throw new IllegalStateException();
var item = items[--count];
items[count] = 0;
return item;
}
public int peek() {
if (isEmpty())
throw new IllegalStateException();
return items[count - 1];
}
public int min() {
if (isEmpty())
throw new IllegalStateException();
var range = Arrays.copyOfRange(items, 0, count);
int min = range[0];
for (int item : range) {
if (item < min)
min = item;
}
return min;
}
private void resizeArray() {
if (size == count) {
size = size * 2;
int[] newItems = new int[size];
for (int x = 0; x <= count - 1; x++) {
newItems[x] = items[x];
}
items = newItems;
}
}
public boolean isEmpty() {
return count == 0;
}
@Override
public String toString() {
var range = Arrays.copyOfRange(items, 0, count);
return Arrays.toString(range);
}
}