SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Chapter:
List And Iterator Adts
Exercise:
Exercises
Question:2 | ISBN:9781118771334 | Edition: 6

Question

Give an implementation of the stack ADT using an array list for storage.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

PROGRAM CODE:

import java.util.ArrayList;
import java.util.EmptyStackException;

public class Stack {
    private ArrayList<Integer> stack;

    public Stack() {
        stack = new ArrayList<>();
    }

    // Check if the stack is empty
    public boolean isEmpty() {
        return stack.isEmpty();
    }

    // Push an element onto the top of the stack
    public void push(int element) {
        stack.add(element);
    }

    // Pop and return the top element from the stack
    public int pop() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return stack.remove(stack.size() - 1);
    }

    // Return the top element of the stack without removing it
    public int peek() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return stack.get(stack.size() - 1);
    }

    // Return the number of elements in the stack
    public int size() {
        return stack.size();
    }

    public static void main(String[] args) {
        Stack stack = new Stack();

        stack.push(5);
        stack.push(10);
        stack.push(15);

        System.out.println("Stack size: " + stack.size());
        System.out.println("Top element: " + stack.peek());

        int poppedElement = stack.pop();
        System.out.println("Popped element: " + poppedElement);
        System.out.println("Stack size after pop: " + stack.size());
    }
}

OUTPUT OF THE PROGRAM CODE:

Stack size: 3
Top element: 15
Popped element: 15
Stack size after pop: 2

 

0 0

Discussions

Post the discussion to improve the above solution.