-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_arraylist.java
More file actions
109 lines (84 loc) · 1.74 KB
/
stack_arraylist.java
File metadata and controls
109 lines (84 loc) · 1.74 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
public class StackUse {
public static void main(String[] args) throws StackFullException {
StackUsingArray stack = new StackUsingArray(3);
for(int i = 1; i <= 5; i++){
stack.push(i);
}
while(!stack.isEmpty()){
try {
System.out.println(stack.pop());
} catch (StackEmptyException e) {
// Never reach here
}
}
}
}
class StackUsingArray {
private int data[];
private int top; // is the index of topmost element of stack
public StackUsingArray() {
data = new int[10];
top = -1;
}
public StackUsingArray(int capacity) {
data = new int[capacity];
top = -1;
}
public boolean isEmpty(){
// if(top == -1){
// return true;
// }else{
// return false;
// }
return (top == -1);
}
public int size(){
return top + 1;
}
public int top() throws StackEmptyException{
if(size() == 0){
//StackEmptyException
StackEmptyException e = new StackEmptyException();
throw e;
}
return data[top];
}
public void push(int elem) throws StackFullException{
if(size() == data.length){
// Stack Full
StackFullException e = new StackFullException();
throw e;
}
top++;
data[top] = elem;
}
public int pop() throws StackEmptyException{
if(size() == 0){
//StackEmptyException
StackEmptyException e = new StackEmptyException();
throw e;
}
int temp = data[top];
top--;
return temp;
}
}
class StackEmptyException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
}
private void doubleCapacity() {
int temp[] = data;
data = new int[2 * temp.length];
for(int i = 0; i <= top; i++){
data[i] = temp[i];
}
}
class StackFullException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
}