-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathStack.java
More file actions
63 lines (49 loc) · 1.15 KB
/
Stack.java
File metadata and controls
63 lines (49 loc) · 1.15 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
package lecture9a13;
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 int size() {
return this.tos + 1;
}
public boolean isEmpty() {
return this.size() == 0;
}
public boolean isFull() {
return size() == this.data.length;
}
public void push(int item) throws Exception {
if (this.size() == this.data.length)
throw new Exception("Stack is Full");
this.tos++;
this.data[this.tos] = item;
}
public int pop() throws Exception {
if(this.size()==0)
throw new Exception("Stack is Empty");
int rv = this.data[this.tos];
this.tos--;
return rv;
}
public int peek() throws Exception {
if(this.size()==0) {
throw new Exception("Stack is Empty");
}
return this.data[this.tos];
}
public void display() {
System.out.println("---------------------------------------------");
for (int i = this.tos; i >=0; i--) {
System.out.print(this.data[i] +" ");
}
System.out.println(".");
System.out.println("----------------------------------------------");
}
}