Я создал стек, используя array, и создал три его основные операции: PUSH , POP и Top. где PUSH – это операция вставки. POP – это операция удаления. Top просто возвращает переменную в верхней части стека. Я также добавил логику состояния “Переполнения” и “Недостаточного потока” с некоторой обработкой исключений. Код подробно объясняется с помощью комментариев.
Чтобы подправить входные данные и проверить операции кликните сюда
Код
import java.util.*; public class Template { static int max_size; static int top ; int temp; static int arr[]; public void Stack(int size) { arr = new int[size]; max_size = arr.length; top = -1; } public boolean empty() { //checking if stack is empty . return temp == -1; } public boolean full() { //checking if stack is full . return top + 1 == max_size; } public void push(int Ip) {//PUSH operation if(top <= max_size) { top++; } try { //bit of exception handling while insertion/PUSH operation if(top >max_size) { throw new ArrayIndexOutOfBoundsException(); } else if(empty()|| top<=max_size) { arr[top] = Ip; } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Stack overflow"); top--; } } public void pop() { // POP temp = top; if(top > -1) { // stop top from further decrementing if already -1, top--; // if not it will interfere with push operation. }else { temp--;} try { //bit of exception handling while deletion/POP operation if(temp < -1) throw new ArrayIndexOutOfBoundsException(); }catch (ArrayIndexOutOfBoundsException e) { System.out.println("Stack underflow"); } } public void Top() { System.out.println(arr[top] +" at index "+ top); } public static void main(String[] args) { Template t = new Template(); t.Stack(4); t.push(6); t.Top(); // <---- Return Top variable of Stack t.pop(); // <--- 6 is removed from the stack so stack will be empty t.pop(); // <-- so removing element from empty stack will return "UNDERFLOW" t.push(101); t.Top(); // <---- Return Top variable of Stack t.push(10); t.Top(); // <---- Return Top variable of Stack t.push(112); t.Top(); // <---- Return Top variable of Stack t.push(14); //<----- stack will be full at this point t.Top(); t.push(146); // so if you push anything it will print "OVERFLOW" t.push(110); t.Top(); // <---- Return Top variable of Stack } }
Оригинал: “https://dev.to/gouravmpk/implementation-of-stacks-using-array-in-java-599h”