Question: Sometimes it is useful to define operations on ADT without changing the type definition itself. For example, you might want to print the elements in

Sometimes it is useful to define operations on ADT without changing the type definition itself. For example, you might want to print the elements in a stack without actually adding a method to the Stack ADT (you may not even have access to it). To explore this, use the Stack class provided by Java (in java. util) and the test program below, StackTest.java.

  1. Add the following three static methods to the StackTest class. You may define a local Stack or PriorityQueue object (no arrays or ArrayList objects) to help you keep things in order and not lose them when they're popped off the stack! Use paper/pen to visualize your logic/algorithm first to help you formulate each method below.
    1. void printStack(Stack s)—prints the elements in stack s from top to bottom. When the print stack returns, s should be unchanged.
    2. Stack reverse stack(Stack s)—returns a new stack whose elements are backward from those in s. Again, s is unchanged.
    3. Stack remove element(Stack s, int val)—returns a new stack whose elements are the same as those in s (and in the same order) except that all occurrences of val have been removed. Again, s is unchanged.
  1. Modify the main method to test these methods by converting each TODO into a Java statement. You should modify the stack instantiation line as well to match the Stack class from the API. Be sure you print enough information to see if they’re working!

/**

* StackTest.java

* A simple driver to test methods to print a stack, reverse

* the elements in a stack, and remove elements in a stack.

* @author

* @version

*/

import java.util.Stack;

public class StackTest

{

public static void main(String[] args)

{

// Declare and instantiate a stack

Stack stack = new Stack();

// Push some stuff on to the stack

for (int i=0; i<10; i++)

stack.push(i);

stack.push(5);

// REMOVE ALL "TODO"s WHEN DONE, INCLUDING THIS LINE
// TODO: call printStack to print the stack

// TODO: call reverseStack to reverse the stack

// TODO: call printStack to print the stack again

// TODO: call removeElement to remove all occurrences of the value 5 - save the stack returned from this call

// TODO: call printStack to print the stack after the removal of 5s

}

}

Step by Step Solution

3.51 Rating (151 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

Answers Here I am adding the source code of the program along ... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Mechanical Engineering Questions!