Untitled Note

By: Anonymous10/31/20232 views Public Note
public class StackUsingArray { private int maxSize; private int top; private int[] stackArray; // Constructor to initialize the stack with a given maximum size public StackUsingArray(int size) { maxSize = size; stackArray = new int[maxSize]; top = -1; // Initialize the top to -1 when the stack is empty } // Check if the stack is empty public boolean isEmpty() { return (top == -1); } // Check if the stack is full public boolean isFull() { return (top == maxSize - 1); } // Push an element onto the stack public void push(int value) { if (isFull()) { System.out.println("Stack is full. Cannot push " value); } else { stackArray[ top] = value; System.out.println(value " pushed onto the stack."); } } // Pop an element from the stack public int pop() { if (isEmpty()) { System.out.println("Stack is empty. Cannot pop."); return -1; // Return a sentinel value to indicate an error } else { int poppedValue = stackArray[top--]; System.out.println(poppedValue " popped from the stack."); return poppedValue; } } // Peek at the top element without removing it public int peek() { if (isEmpty()) { System.out.println("Stack is empty."); return -1; // Return a sentinel value to indicate an error } else { return stackArray[top]; } } // Display the elements in the stack public void display() { if (isEmpty()) { System.out.println("Stack is empty."); } else { System.out.print("Stack (top to bottom): "); for (int i = top; i >= 0; i--) { System.out.print(stackArray[i] " "); } System.out.println(); } } public static void main(String[] args) { StackUsingArray stack = new StackUsingArray(5); stack.push(10); stack.push(20); stack.push(30); stack.display(); System.out.println("Top element: " stack.peek()); stack.pop(); stack.display(); System.out.println("Is the stack empty? " stack.isEmpty()); System.out.println("Is the stack full? " stack.isFull()); } }

Want to create your own notes?

Join thousands of users writing securely on ProNotepad.