-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStackArrayList.java
72 lines (63 loc) · 1.32 KB
/
StackArrayList.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
import java.util.Arrays;
import java.util.EmptyStackException;
public class StackA<T>{
private T[] arr;
private int size;
public StackA(){
arr= (T[]) new Object[10];
}
public StackA(T value){
arr[size]=value;
size++;
}
public void insureCapacity(){
if(arr.length==size){
T[] copy= Arrays.copyOf(arr,2*size);
arr=copy;
}
}
//o(1)
public boolean isEmpty(){
return size==0;
}
//o(1)
public T peek(){
if(size==0)
throw new EmptyStackException();
return arr[size-1];
}
//o(1)
public void push(T value){
insureCapacity();
arr[size]=value;
size++;
}
//o(1)
public T pop(){
if(size==0)
throw new EmptyStackException();
size--;
T removedval=arr[size];
return removedval;
}
//o(n)
public int search(T value){
for(int i=size-1;i>=0;i--){
if(arr[i].equals(value))
return size - i;
}
return -1;
}
public String toString(){
String st="";
for(int i=0;i<size;i++)
st+=arr[i]+" ";
return st;
}
public T[] getArr() {
return arr;
}
public int getSize() {
return size;
}
}