-
Notifications
You must be signed in to change notification settings - Fork 303
/
Copy pathArrayStack.java
88 lines (77 loc) · 1.67 KB
/
ArrayStack.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.util.EmptyStackException;
/**
* An array implementation of the Stack interface.
*/
public class ArrayStack<T> implements Stack<T> {
private static final int DEFAULT_CAPACITY = 10;
private T[] array;
private int top;
/**
* Constructs an empty stack with the default capacity.
*/
public ArrayStack() {
this(DEFAULT_CAPACITY);
}
/**
* Constructs an empty stack with the specified capacity.
*
* @param capacity the initial capacity of the stack
*/
public ArrayStack(int capacity) {
array = (T[]) new Object[capacity];
top = -1;
}
/**
* {@inheritDoc}
*/
@Override
public void push(T element) {
if (top == array.length - 1) {
expandCapacity();
}
top++;
array[top] = element;
}
/**
* {@inheritDoc}
*/
@Override
public T pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
T element = array[top];
array[top] = null;
top--;
return element;
}
/**
* {@inheritDoc}
*/
@Override
public T peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return array[top];
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEmpty() {
return top == -1;
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return top + 1;
}
private void expandCapacity() {
T[] newArray = (T[]) new Object[array.length * 2];
System.arraycopy(array, 0, newArray, 0, array.length);
array = newArray;
}
}