Sometimes it is useful to define operations on ADT without changing the type definition itself. For example,
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 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.
- 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.
- void printStack(Stack s)—prints the elements in stack s from top to bottom. When the print stack returns, s should be unchanged.
- Stack reverse stack(Stack s)—returns a new stack whose elements are backward from those in s. Again, s is unchanged.
- 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.
- 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
}
}
Microeconomics
ISBN: 978-0321866349
14th canadian Edition
Authors: Christopher T.S. Ragan ,Richard G Lipsey