-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathStackUsingArrays.java
More file actions
58 lines (48 loc) · 1.19 KB
/
Copy pathStackUsingArrays.java
File metadata and controls
58 lines (48 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
package stacks;
public class StackUsingArrays {
private int[] data;
// index of the top-most element
private int top;
public StackUsingArrays() {
data = new int[10];
top = -1;
}
public void push(int element) {
// if the stack is full
if (top == data.length - 1) {
doubleCapacity();
}
data[++top] = element;
}
private void doubleCapacity() {
System.out.println("Doubling the Capacity...");
int[] tmp = data;
data = new int[2 * tmp.length];
for (int i = 1; i < tmp.length; i++) {
data[i] = tmp[i];
}
}
public int size() {
return top + 1;
}
public int top() {
// stack is empty
if (top == -1) {
throw new IllegalArgumentException("Stack Underflow");
}
return data[top++];
}
public int pop() {
// stack is empty
if (top == -1) {
throw new IllegalArgumentException("Stack Underflow");
}
/*int tmp = data[top];
top -= 1;
return tmp;*/
return data[top--];
}
public boolean isEmpty() {
return top == -1;
}
}