Java: Stack - 01

Problem: -

  1. Write a program to perform push and pop operations.

Solution: -

1. Write a program to perform push and pop operations.

import java.util.Scanner;
import java.util.ArrayList;

class Stacks {

static class Stack {
    static ArrayList<Integer> array = new ArrayList<>();

static void push(int data) {
    array.add(data);
}

static void pop() {
    int num = array.get(array.size()-1);
    System.out.print("\nRemoved Element is: " + num + "\n");
    array.remove(array.size()-1);
}

static void display() {
    int num = array.size()-1;

    System.out.println("\nElement of Stacks:");
    for (int i = num; i >= 0; i--)
    {
    System.out.println(array.get(i));
    }
}
}

static void pushData() {
    Scanner scan = new Scanner(System.in);
    Stack stack = new Stack();
    System.out.print("Enter data: ");
    int data = scan.nextInt();

    stack.push(data);
}

public static void main(String args[]) {
    Scanner scan = new Scanner(System.in);
    Stack stack = new Stack();
    int choice;

do {
    System.out.print("\nSTACK DASHBOARD: \n1. Enter element in Stack.\n2. Remove element in Stack.\n3. Display Stack Element.\n4. Exit.");

    System.out.print("\n\nEnter your choice: ");
    choice = scan.nextInt();

switch(choice) {
case 1: pushData();
break;
case 2: stack.pop();
break;
case 3: stack.display();
break;
case 4: System.out.println("Exiting...");
break;
default: System.out.println("You entered wrong choice.");
break;
}
} while(choice != 4);

}
}

Output: -

Mj Mausam

Post a Comment

Previous Post Next Post