forked from Abraarkhan/Java_Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstackArrayApp.java
82 lines (73 loc) · 1.91 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
public class stackArrayapp {
/**
* @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(6);
sa.push(8);
sa.push(9);
sa.push(3);
sa.push(2);
sa.display();
sa.push(1);
try{
int k=sa.peek();
System.out.println("peek " +k);
System.out.println("popped an item "+sa.pop());
System.out.println("popped an item "+sa.pop());
}catch (Exception e){
}
sa.display();
}
}
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) {//before inserting check whether the array is full
//top++;
//stackData[top]=item;
if(isFull()){
System.out.println("Stack is full");
return;
}
stackData[++top]=item;
}
public int pop() throws Exception {
/*int temp=stackData[top];
top--;
return temp;*/
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 give the 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 class StackArray