-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathStackUsingArray.java
60 lines (48 loc) Β· 1008 Bytes
/
StackUsingArray.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
package section10_Stacks;
public class StackUsingArray {
private int tos;
private int[] data;
public StackUsingArray() {
this.tos = -1;
// initializing with 5 capacity
data = new int[5];
}
public StackUsingArray(int capacity) {
this.tos = -1;
data = new int[capacity];
}
public int size() {
return tos + 1;
}
public boolean isEmpty() {
return size() == 0;
}
public boolean isFull() {
return size() == data.length;
}
public void push(int item) throws Exception {
if (isFull())
throw new Exception("Stack is full...");
tos++;
data[tos] = item;
}
public int pop() throws Exception {
if (isEmpty())
throw new Exception("Stack is empty...");
int temp = data[tos];
data[tos] = 0;
tos--;
return temp;
}
public int peek() {
return data[tos];
}
public void display() {
System.out.println("displaying stack...");
for (int i = tos; i >= 0; i--) {
System.out.println(data[i]);
System.out.println("-----");
}
System.out.println();
}
}