From e890ff8e60d665c217d032de328c687f246a5b69 Mon Sep 17 00:00:00 2001 From: ziameraj16 Date: Wed, 13 Jan 2021 20:43:40 +0000 Subject: Java solution for Challenge 095 --- challenge-095/ziameraj16/java/DemoStack.java | 88 ++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 challenge-095/ziameraj16/java/DemoStack.java (limited to 'challenge-095/ziameraj16/java/DemoStack.java') diff --git a/challenge-095/ziameraj16/java/DemoStack.java b/challenge-095/ziameraj16/java/DemoStack.java new file mode 100644 index 0000000000..1fce9e3d83 --- /dev/null +++ b/challenge-095/ziameraj16/java/DemoStack.java @@ -0,0 +1,88 @@ +import java.util.*; + +public class DemoStack { + + private static Scanner scanner = new Scanner(System.in); + + private static final int MAX_SIZE = 1000; + int arr[] = new int[MAX_SIZE]; + int top = -1; + + public static void main(String[] args) { + DemoStack demoStack = new DemoStack(); + System.out.println("Stack Example"); + while (true) { + iterate(demoStack); + } + } + + private static void iterate(DemoStack demoStack) { + System.out.println(String.join("\n", + "\n####################################", + "To push into stack - `push `", + "To pop from the stack - `pop`", + "To find the top element - `top`", + "To find the minimum element - `min`", + "To exit - `exit`", + "####################################\n")); + + final String[] options = scanner.nextLine().toLowerCase().split(" "); + if (options[0].equals("push")) { + demoStack.push(Integer.parseInt(options[1])); + } else if (options[0].equals("pop")) { + demoStack.pop(); + } else if (options[0].equals("top")) { + demoStack.top(); + } else if (options[0].equals("min")) { + demoStack.min(); + } else if (options[0].equals("exit")) { + System.out.println("Bye!!!"); + System.exit(1); + } else { + System.out.println("Invalid option: " + options[0]); + } + } + + public boolean push(int number) { + if (top == MAX_SIZE - 1) { + System.err.println("Stack is full"); + return false; + } + arr[++top] = number; + System.out.println(String.format("Number %s added to the stack", number)); + return true; + } + + public int pop() { + if (top < 0) { + System.err.println("No element to pop"); + return Integer.MIN_VALUE; + } + int num = arr[top--]; + System.out.println("Element popped: " + num); + return num; + } + + public int top() { + if (top < 0) { + System.err.println("Stack is empty"); + return Integer.MIN_VALUE; + } + int num = arr[top]; + System.out.println("Top element: " + num); + return num; + } + + public int min() { + if (top < 0) { + System.err.println("Stack is empty"); + return Integer.MIN_VALUE; + } + final int[] copyArr = Arrays.copyOf(arr, top + 1); + Arrays.sort(copyArr); + int min = copyArr[0]; + System.out.println("Minimum number in stack: " + min); + return min; + } +} + -- cgit