-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
72 lines (55 loc) · 1.19 KB
/
Stack.java
File metadata and controls
72 lines (55 loc) · 1.19 KB
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
package com.wang.code.one;
import java.util.Iterator;
/**
* @author WANGJJ
* @date 2020/04/17
*/
public class Stack<T> implements Iterable<T>{
private T[] ts;
private int n;
public Stack(int cap){
ts = (T[]) new Object[cap];
}
public Boolean isEmpty(){
return n == 0;
}
public int size(){
return n;
}
public T pop(){
T t = ts[--n];
ts[n] = null;
if (n > 0 && n < ts.length / 4) {
resize(ts.length / 2);
}
return t;
}
public void push(T t){
if (n == ts.length) {
resize(2 * ts.length);
}
ts[n++] = t;
}
@Override
public Iterator<T> iterator(){
return new ReverseArrayIterator();
}
private void resize(int max) {
T[] tsNew = (T[]) new Object[max];
for (int i = 0; i < n; i++){
tsNew[i] = ts[i];
}
ts = tsNew;
}
private class ReverseArrayIterator implements Iterator<T> {
int i = n;
@Override
public boolean hasNext() {
return i > 0;
}
@Override
public T next() {
return ts[--i];
}
}
}