Write a Java program to implement the Stack using arrays. Write Push(), Pop(), and Display() methods to demonstrate its working.
1 package program1.stack; 2 3 public class MyStack { 4 private int[] stk; 5 private int top; 6 private int maxSize; 7 8 public MyStack(int maxSize) { 9 this.stk = new int[maxSize]; 10 this.top = -1; 11 this.maxSize = maxSize; 12 } 13 14 boolean isStackFull() { 15 return (top == maxSize - 1); 16 } 17 18 boolean isStackEmpty() { 19 return (top == -1); 20 } 21 22 public void push(int item) { 23 this.stk[++top] = item; 24 } 25 26 public int pop() { 27 return (this.stk[top--]); 28 } 29 30 public void displayStack() { 31 System.out.println("The Stack Items are ..."); 32 33 for (int i = this.top; i >= 0; --i) { 34 System.out.println(this.stk[i]); 35 } 36 } 37} 38 39package program1.stack; 40 41import java.util.Scanner; 42 43public class MyStackDemo { 44 45 public static void main(String[] args) { 46 47 Scanner s = new Scanner(System.in); 48 49 System.out.println("Enter Stack Size: "); 50 int maxSize = s.nextInt(); 51 52 MyStack stk = new MyStack(maxSize); 53 54 System.out.println( 55 "Stack operations are" + "\n" + "1.Push" + "\t" + "2.POP" + "\t" + "3.Display" + "\t" + "4.Exit"); 56 57 for (;;) { 58 System.out.println("\nEnter your choice: "); 59 int ch = s.nextInt(); 60 61 switch (ch) { 62 case 1: 63 if (stk.isStackFull()) { 64 System.out.println("Stack is Overflow"); 65 } else { 66 System.out.println("Enter an Item to be pushed: "); 67 int ele = s.nextInt(); 68 stk.push(ele); 69 } 70 break; 71 72 case 2: 73 if (stk.isStackEmpty()) { 74 System.out.println("Stack is Underflow"); 75 } else { 76 System.out.println("Popped Item: " + stk.pop()); 77 } 78 break; 79 80 case 3: 81 if (stk.isStackEmpty()) { 82 System.out.println("Stack is Empty"); 83 } else { 84 stk.displayStack(); 85 } 86 break; 87 88 case 4: 89 System.exit(0); 90 break; 91 } 92 } 93 } 94} |
OUTPUT:
Enter Stack Size:
5
Stack operations are
1.Push 2.POP 3.Display 4.Exit
Enter your choice:
1
Enter an Item to be pushed:
10
Enter your choice:
1
Enter an Item to be pushed:
20
Enter your choice:
1
Enter an Item to be pushed:
30
Enter your choice:
1
Enter an Item to be pushed:
40
Enter your choice:
1
Enter an Item to be pushed:
50
Enter your choice:
1
Stack is Overflow
Enter your choice:
3
The Stack Items are ...
50
40
30
20
10
Enter your choice:
2
Popped Item: 50
Enter your choice:
2
Popped Item: 40
Enter your choice:
3
The Stack Items are ...
30
20
10
Enter your choice:
2
Popped Item: 30
Enter your choice:
2
Popped Item: 20
Enter your choice:
2
Popped Item: 10
Enter your choice:
3
Stack is Empty
Enter your choice:
2
Stack is Underflow
Enter your choice:
1
Enter an Item to be pushed:
100
Enter your choice:
1
Enter an Item to be pushed:
200
Enter your choice:
3
The Stack Items are ...
200
100
Enter your choice:
4
No comments:
Post a Comment