March 04, 2024

Java Problems Solutions: Implement a Stack in Java


public class MyStack {
/* A stack is a data structure that follows the Last In First Out (LIFO) principle,
meaning the last element added to the stack will be the first one to be removed.*/
    private int maxSize; // Maximum size of the stack
    private String[] stackArray; // Array to hold the stack elements
    private int top; // Index of the top element in the stack

    public static void main(String[] args) {// Test the stack
    	MyStack s = new MyStack(3);
    	s.push("A");
    	s.push("B");
    	s.push("C");
    	System.out.println(s.isFull() ? "Stack full" : "Stack not full");
    	if (!s.isFull()) {
            s.push("D");
        } else {
            System.out.println("Cannot push onto a full stack.");
        }
    	System.out.println("Output: " + s.pop()); // Should output the last element
        System.out.println("Output: " + s.pop()); // Should output the last element     
        System.out.println("Output: " + s.pop()); // Should output the last element
        System.out.println(s.isEmpty() ? "Stack empty" : "Stack not empty");   
    	if (!s.isEmpty()) {
            s.pop();
        } else {
            System.out.println("Cannot pop from an empty stack.");
        }
    }
    
    public MyStack(int size) {// Constructor to initialize the stack with a specified size
        maxSize = size;
        stackArray = new String[maxSize];
        top = -1; // Initialize top as -1 indicating an empty stack
    }

    public void push(String value) {// Method to push an element onto the stack
        // Increment top and add the element to the stack
        stackArray[++top] = value;
    }

    public String pop() {// Method to pop an element from the stack
        // Retrieve the element at the top and decrement top
        return stackArray[top--];
    }

    public boolean isEmpty() {// Method to check if the stack is empty
        return (top == -1);
    }

    public boolean isFull() {// Method to check if the stack is full
        return (top == maxSize - 1);
    }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please. View my following video


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.