COMP2247 - Algorithms and Data Structures

Syllabus Software Installation Assignments Tests
Lectures and Labs
**Back to Full Menu**

Stacks My Stack Program
StackInterface.java
MyArrayListStack.java
MyArrayListStackProjectClient.java
EmptyStackException.java
Postfix Program Palindrome Program



MyArrayListStack Program


Description

This program builds an ArrayList based generic stack data structure.

Associated Concepts:

Stack

Algorithm:

StackInterface Java interface

It defines a Java interface StackInterface which includes five abstract methods.

push(), pop(), peek(), size(), and isEmpty().

MyArrayListStack class

It implements StackInterface.

Two private data members: a generic ArrayList object and a variable called top to indicate the number of the objects in the stack.

Constructor:

Initialize the data members:

- Create the generic ArrayList object.

- Set the variable top to -1.

size(), isEmpty(), push(), peek(), pop(), and toString() methods.

size() method

Return the number of objects in the stack.

isEmpty() method

Return true if the stack is empty; false otherwise.

void push(E object) method

1. Increment the value of top variable by 1.

2. Add the object onto the top of the stack.

E peep() method

1. Check for the empty stack.

2. Return the object at the top of the stack.

E pop() method

1. Check for the empty stack.

2. Remove the top object from the stack.

3. Decrement the value of top variable.

4. Return the removed object.

String toString() method

1. Declare a string to store the result.

2. In a loop, retrieve each object in the stack and add it to the result.

3. Return the result after the loop is ended.

Client program

Create a MyArrayListStack object.

Call the methods defined in the MyArrayListStack class to test them.

EmptyStackException class

Extend the RuntimeException class.

Invoke the superclass' constructor in the constructor.

Source Code

StackInterface class



MyArrayListStack class



Client program



EmptyStackException class



Sample Run



Video