Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

CPT102 – Data Structures

Lab 2 Stack ADT

Aim

Understand java generic type and Stack ADT.

Resources

All Java files you need are found on Learning Mall.

Tips

Check lecture notes for lecture 4 to understand Stack before starting.

Stack Implementation

At this Lab session, we are going to implement the ArrayStack class, which uses array to store the      data of our Stack structure. An ArrayStack is a generic collection of references to objects (objects has the same type). The collection represents a last-in-first-out (LIFO) stack of objects.

You will have to use ArrayBag.java from last lab as reference.

Task: Create a class called ArrayStack (Similar to ArrayBag class).

Your class should contain:

     An array called data to store the elements. An attribute manyItems stores how many items

are in the stack.

     Two constructers and all the methods in below picture.

 

Note:

     clone():

o Generate a copy of this array stack. Please refer to ArrayBag class, we will discuss about this method in detail in the coming tutorial.

Returns: a copy of the stack.

     peek():

o Looks at the object at the top of this stack without removing it from the stack.

Returns: the object at the top of this stack (the last item of the array).

Throws:EmptyStackException- if this stack is empty.

     pop():

o Removes the object at the top of this stack and returns that object as the value of this function.

Returns: The object at the top of this stack (the last item of the array).

Throws:EmptyStackException- if this stack is empty.

     push():

o Pushes an item onto the top of this stack. This has exactly the same effect as add an element to the stack.

Parameters: item - the item to be pushed onto this stack.

Returns: the item argument.

     remainedCapacity():

o Find out how many items can be pushed to the stack still.

Returns: the remained capacity of the stack.

Test:

Write a test class similar to below example to test your methods.

 

Extra:

1.    Have a look the API of java.util.LinkedList class. If you use LinkedList to implement our Stack, the implementation of stack will be very simple. See what methods (if we use LinkedList to   store the data) you can use to implement a stack.

2.    Compare below two structures. Discuss with your friends and find out what are the difference of these two ADT.

 

Note: If you cannot finish all the tasks, please do them as homework.