-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathStack.java
More file actions
62 lines (51 loc) · 1.13 KB
/
Stack.java
File metadata and controls
62 lines (51 loc) · 1.13 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
package Algorithms_Java;
import java.util.Arrays;
public class Stack {
int[] data;
int tos = -1;
public Stack(int capacity) {
this.data = new int[capacity];
}
public Stack() {
this(5);
}
public Stack(int[] arr) { //this will add reverse elements in stack
this.data=new int[arr.length];
//this.data=Arrays.copyOf(arr, arr.length);
this.tos=arr.length-1;
}
public int size() {
return this.tos + 1;
}
public boolean isEmpty() {
return this.size() == 0;
}
public void push(int value) throws Exception{
if (this.tos == this.data.length - 1) {
throw new Exception("Stack Is Full");
}
this.tos++;
this.data[this.tos] = value;
}
public int pop() throws Exception{
if (this.tos == -1) {
throw new Exception("Stack Is Empty");
}
int deldata = this.data[this.tos];
this.data[this.tos] = 0;
this.tos--;
return deldata;
}
public int top() throws Exception{
if (isEmpty()) {
throw new Exception("Stack Is Empty");
}
return this.data[this.tos];
}
public void display() {
for (int i = this.tos; i >= 0; i--) {
System.out.print(this.data[i] + "->");
}
System.out.println("End");
}
}