Push Operation
In this Operation we are going to insert the Data into the Stack.
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | public boolean push(int[] stackAry,int elementToInsert) {
boolean insertFlag = false;
if(top == stackAry.length-1) {
insertFlag = false;
}
else {
top++;
stackAry[top] = elementToInsert;
insertFlag = true;
}
return insertFlag;
}
|
Pop Operation
In this Operation we are going to delete the Data into the Stack.
1
2
3
4
5
6
7
8
9
10
11
12 | public boolean pop(int[] stackAry) {
boolean deleteFlag = false;
if(top == -1) {
deleteFlag = false;
}else {
stackAry[top]=0;
top=top-1;
deleteFlag = true;
}
return deleteFlag;
}
|
Print the Stack Data: Normally we call it as Peek
In this Operation we are going to print the all the stack values while using the pop
1
2
3
4
5
6
7
8 | public void printAllValues(int[] stackAry) {
while(top!= -1) {
int temp = top--;
System.out.println(stackAry[temp]);
stackAry[temp]=0;
}
int b=20;
}
|
Complete Code
The following is the whole code to stack operations.
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 | package stackOperations;
public class StackClass {
int top=-1;
public boolean push(int[] stackAry,int elementToInsert) {
boolean insertFlag = false;
if(top == stackAry.length-1) {
insertFlag = false;
}
else {
top++;
stackAry[top] = elementToInsert;
insertFlag = true;
}
return insertFlag;
}
public boolean pop(int[] stackAry) {
boolean deleteFlag = false;
if(top == -1) {
deleteFlag = false;
}else {
stackAry[top]=0;
top=top-1;
deleteFlag = true;
}
return deleteFlag;
}
public void printAllValues(int[] stackAry) {
while(top!= -1) {
int temp = top--;
System.out.println(stackAry[temp]);
stackAry[temp]=0;
}
int b=20;
}
}
|
Main Class Code For Stack
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 | package stackOperations;
public class Main {
public static void main(String[] args) {
int[] stackAry = new int[3];
StackClass obj = new StackClass();
obj.push(stackAry, 1);
obj.push(stackAry, 2);
obj.push(stackAry, 3);
if (obj.pop(stackAry)) {
System.out.println("deleted SuccessFull");
} else {
System.out.println("Not deleted or Stack is Empty");
}
obj.printAllValues(stackAry);
}
}
|
Comments
Post a Comment