This repository has been archived by the owner on Nov 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 151
/
stack.java
110 lines (100 loc) · 2.7 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
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
public class Stack {
/
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
StackArray sa = new StackArray(6);
sa.push(7);
sa.push(3);
sa.push(2);
sa.push(9);
sa.push(8);
sa.display();
sa.push(1);
sa.push(5);
sa.display();
try{
int k = sa.peek();
System.out.println("Peek is "+k);
System.out.println("poped an item :" + sa.pop());
System.out.println("poped an item :" + sa.pop());
System.out.println("poped an item :" + sa.pop());
System.out.println("poped an item :" + sa.pop());
System.out.println("poped an item :" + sa.pop());
System.out.println("poped an item :" + sa.pop());
System.out.println("poped an item :" + sa.pop());
}catch (Exception e){
System.out.println(e.getMessage());
}
Stack s=new Stack();
System.out.print("binary value of 50 is : ");
s.decimalToBinary(50);
}
public void decimalToBinary(int no){
int temp = no;
int count =0;
while(temp!=0){
temp=temp/2;
count++;
}
StackArray myStack = new StackArray(count);
temp = no;
while(temp!=0){
int rem=temp%2;
temp=temp/2;
myStack.push(rem);
}
while(!myStack.isEmpty()){
try{
System.out.print(myStack.pop());
}catch(Exception e){
}
}
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.stackData = new int[s];
this.maxSize = s;
this.top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize - 1;
}
public void push(int item) {
if (isFull()){
System.out.println("Stack is full cannot push");
return;
}
stackData[++top] = item;
}
public int pop() throws Exception{
if(isEmpty()){
throw new Exception ("Stack is empty cannot pop");
}
return stackData[top--];
}
public int peek() throws Exception {
if(isEmpty()){
throw new Exception("Stack is empty cannot peek");
}
return stackData[top];
}
public void display() {
System.out.println("Start printing stack data.....");
for(int i=top;i>=0;i--){
System.out.println(stackData[i]);
}
System.out.println("End printing stack data.....");
System.out.println( );
}
}