-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathStackArrayApp.java
122 lines (100 loc) · 2.93 KB
/
StackArrayApp.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import java.util.logging.Level;
import java.util.logging.Logger;
public class StackArrayApp {
public static void main(String[] args) {
StackArrayApp s = new StackArrayApp();
System.out.print("Binary value of 50 is : ");
s.decToBin(50);
}
public void decToBin(int n) {
int temp = n, cnt = 0;
while (temp != 0) {
temp = temp / 2;
cnt++;
}
StackArray myStack = new StackArray(cnt);
temp = n;
while (temp != 0) {
int rem = temp % 2;
temp = temp / 2;
myStack.push(rem);
}
while (!myStack.isEmpty()) {
try {
System.out.print(myStack.pop());
} catch (Exception ex) {
System.out.println(ex);
}
}
System.out.println("");
}
}
class StackArray {
private int maxSize; //size of stack array
private int[] stackData;
private int top; //top of stack
//-------------------------------------------------------------------------
public StackArray(int s) {
this.maxSize = s;
this.stackData = new int[s];
this.top = -1;
}
public boolean isEmpty() {
return (this.top == -1);
}
public boolean isFull() {
return (this.top == maxSize - 1);
}
public void push(int item) {
if (this.isFull()) {
System.out.println("Stack is full");
} else {
this.top++;
this.stackData[this.top] = item;
}
}
public int pop() throws Exception {
if (this.isEmpty()) {
//System.out.println("stack is empty. nothing to return");
throw new Exception("stact is empty , cannot pop");
}
int temp = stackData[top];
top--;
return temp;
}
public int peek() {
if (this.isEmpty()) {
System.out.println("stack is empty. nothing toreturn");
return -1;
}
int temp = stackData[top];
return temp;
}
public void display() {
System.out.println("Data within the stack");
for (int i = this.top; i > -1; i--) {
System.out.print(this.stackData[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) {
StackArray st = new StackArray(5);
st.push(3);
st.push(6);
st.push(1);
st.push(2);
st.display();
System.out.println("peek : " + st.peek());
try {
int k = st.pop();
System.out.println("popped : " + k);
System.out.println("popped : " + st.pop());
System.out.println("popped : " + st.pop());
//System.out.println("popped : "+st.pop());
//System.out.println("popped : "+st.pop());
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
st.display();
}
}