-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathArrayStack.java
More file actions
57 lines (43 loc) · 869 Bytes
/
ArrayStack.java
File metadata and controls
57 lines (43 loc) · 869 Bytes
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
public class ArrayStack<T>{
/*The underlying datastructure is array*/
private final int DEFAULT_CAPACITY = 100;
private int top;
private T[] stack;
public ArrayStack<T>(){
this. top = 0;
this.stack = new T[DEFAULT_CAPACITY];
}
public ArrayStack<T>(int capacity){
this. top = 0;
this.stack = new T[capacity];
}
public T pop(){
if (stack.isEmpty())
{throw.EmptyStackException("stack");}
top --;
T element = stack[top];
stack[top] = null;
return element;
}
public void push(T element){
if (stack.isFull()){
stack = expandStack();
}
++top;
stack[top] = element;
}
public T peek(){
return stack[top];
}
public boolean isEmpty(){
return stack.size() == 0 ? true:false;
}
public T[] expandStack(){
int size = stack.size();
T[] expandStack = new T[size *2];
for (int i=0;i < size;i++){
expandStack[i] = stack[i]
}
return expandStack;
}
}