forked from LuanDevecchi/HacktoberfestAlgo2019
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.java
72 lines (50 loc) · 1.01 KB
/
Stack.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
72
public class Stack {
protected int data[];
protected int tos;
public Stack() {
this.data = new int[5];
this.tos = -1;
}
public Stack(int cap) {
this.data = new int[cap];
this.tos = -1;
}
public void push(int item) throws Exception {
if (isFull()) {
throw new Exception("Stack Overflow");
}
this.tos++;
this.data[this.tos] = item;
}
public int pop() throws Exception {
if (isEmpty()) {
throw new Exception("Stack Underflow");
}
int rv = this.data[this.tos];
this.data[this.tos] = 0;
this.tos--;
return rv;
}
public int peek() throws Exception {
if (isEmpty()) {
throw new Exception("Stack Underflow");
}
int rv = this.data[this.tos];
return rv;
}
public int size() {
return this.tos + 1;
}
public boolean isFull() {
return this.size() == this.data.length;
}
public boolean isEmpty() {
return this.size() == 0;
}
public void display() {
for (int i = tos; i >= 0; i--) {
System.out.print(this.data[i] + " ");
}
System.out.println();
}
}