-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayStack.java
executable file
·92 lines (74 loc) · 1.81 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
89
90
91
92
package com.example.arrayStack;
import com.example.exceptions.EmptyCollectionException;
import com.example.interfaces.StackADT;
public class ArrayStack<T> implements StackADT<T> {
private static final int DEFAULT_CAPACITY = 100;
private int top;
private T[] stack;
public ArrayStack(int initialCapacity) {
this.top = 0;
this.stack = (T[]) new Object[initialCapacity];
}
public ArrayStack() {
this(DEFAULT_CAPACITY);
}
/**
* {@inheritDoc }
*/
@Override
public void push(T element) {
if (this.stack.length == this.size()) {
expandCapacity();
}
this.stack[top] = element;
this.top++;
}
private void expandCapacity() {
T[] aux = (T[]) new Object[this.stack.length * 2];
System.arraycopy(this.stack, 0, aux, 0, this.top);
this.stack = aux;
}
/**
* {@inheritDoc }
*/
@Override
public T pop() throws EmptyCollectionException {
T toRemove;
if (isEmpty()) {
throw new EmptyCollectionException(EmptyCollectionException.EMPTY_COLLECTION);
}
this.top--;
toRemove = this.stack[this.top];
return toRemove;
}
/**
* {@inheritDoc }
*/
@Override
public T peek() {
return this.stack[this.top - 1];
}
/**
* {@inheritDoc }
*/
@Override
public boolean isEmpty() {
return this.top == 0;
}
/**
* {@inheritDoc }
*/
@Override
public int size() {
return this.top;
}
protected String print() {
StringBuilder s = new StringBuilder();
int i = 0;
while (i != this.top) {
s.append(this.stack[i++]);
s.append(" ");
}
return s.toString();
}
}