Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- program for stack implementation in java using array
- */
- package javaapp;
- import java.io.*;
- import java.util.Scanner;
- class stax {
- private int[] stk;
- private int top;
- // constructor for stax class
- public stax() {
- this.stk = new int[20];
- this.top = -1;
- }
- public void push(int element) {
- top++;
- if (top == 20) {
- System.out.println("Stackfull!!");
- return;
- } else {
- stk[top] = element;
- System.out.println("Item pushed");
- }
- }
- public int pop() {
- if (top == -1) {
- System.out.println("Stackempty!!");
- return 99999; // assuming that 99999 never appears in the stack
- } else {
- int element = stk[top];
- top--;
- return element;
- }
- }
- //display stack contents
- void display() {
- int i;
- for (i = 0; i <= top; i++) {
- System.out.println("" + stk[i]);
- }
- }
- }
- public class stackimpl {
- public static void main(String args[]) {
- int element, cont, choice;
- cont = 1;
- stax s1 = new stax();
- Scanner sc = new Scanner(System.in);
- do {
- System.out.println("THE FOLLOWING CHOICES ARE AVAILIABLE : ");
- System.out.println("1.PUSH AN ELEMENT");
- System.out.println("2.POP AN ELEMENT");
- System.out.println("3.VIEW STACK CONTENTS");
- System.out.println("ENTER YOUR CHOICE : ");
- choice = sc.nextInt();
- switch (choice) {
- case 1:
- System.out.println("ENTER THE ELEMENT TO BE PUSHED : ");
- element = sc.nextInt();
- s1.push(element);
- break;
- case 2:
- element = s1.pop();
- if (element != 99999) {
- System.out.println("THE ELEMENT POPPED IS : " + element);
- }
- break;
- case 3:
- System.out.println("THE ELEMENTS OF STACK ARE : ");
- s1.display();
- break;
- }
- System.out.println("DO YOU WANT TO CONTINUE (1/0): ");
- cont = sc.nextInt();
- } while (cont == 1);
- return;
- }
- }
Add Comment
Please, Sign In to add comment