Question

There is a data structure called a drop-out stack that behaves like a stack in every...

There is a data structure called a drop-out stack that behaves like a stack in every respect except that if the stack size is n, then when the n+1element is pushed, the bottom element is lost. Implement a drop-out stack using links, by modifying the LinkedStack code. (size, n, is provided by the constructor.

Request: Please create a separate driver class, in a different file, that tests on different types of entries and show result of the tests done on the stack. please don' change any given implementation. Thanks a lot!!

############################################### LinkedStack Class ###############################################

/**

* Represents a linked implementation of a stack.

*

* @author Java Foundations

* @version 4.0

*/

public class LinkedStack implements StackADT

{

private int count, maxCapacity;

private LinearNode top;

/**

* Creates an empty stack.

*/

public LinkedStack(int size)

{

count = 0;

top = null;

maxCapacity = size;

}

/**

* Adds the specified element to the top of this stack.

* @param element element to be pushed on stack

*/

public void push(T element)

{

LinearNode temp = new LinearNode(element);

temp.setNext(top);

top = temp;

count++;

}

/**

* Removes the element at the top of this stack and returns a

* reference to it.

* @return element from top of stack

* @throws EmptyCollectionException if the stack is empty

*/

public T pop() throws EmptyCollectionException

{

if (isEmpty())

throw new EmptyCollectionException("stack");

T result = top.getElement();

top = top.getNext();

count--;

return result;

}

/**

* Returns a reference to the element at the top of this stack.

* The element is not removed from the stack.

* @return element on top of stack

* @throws EmptyCollectionException if the stack is empty

*/

public T peek() throws EmptyCollectionException

{

// To be completed as a Programming Project

return null; // temp

}

/**

* Returns true if this stack is empty and false otherwise.

* @return true if stack is empty

*/

public boolean isEmpty()

{

// To be completed as a Programming Project

return true; // temp

}

/**

* Returns the number of elements in this stack.

* @return number of elements in the stack

*/

public int size()

{

// To be completed as a Programming Project

return 0; // temp

}

/**

* Returns a string representation of this stack.

* @return string representation of the stack

*/

public String toString()

{

// To be completed as a Programming Project

return ""; // temp

}

}

############################################### StackADT interface ###############################################

public interface StackADT

{

/**

* Adds the specified element to the top of this stack.

* @param element element to be pushed onto the stack

*/

public void push(T element);

/**

* Removes and returns the top element from this stack.

* @return the element removed from the stack

*/

public T pop();

/**

* Returns without removing the top element of this stack.

* @return the element on top of the stack

*/

public T peek();

/**

* Returns true if this stack contains no elements.

* @return true if the stack is empty

*/

public boolean isEmpty();

/**

* Returns the number of elements in this stack.

* @return the number of elements in the stack

*/

public int size();

/**

* Returns the bottom element in this stack.

* @return bottom element

*/

public T getBottom();

/**

* Returns a string representation of this stack.

* @return a string representation of the stack

*/

public String toString();

}

############################################### LinearNode Class ###############################################

public class LinearNode

{

private LinearNode next;

private T element;

/**

* Creates an empty node.

*/

public LinearNode()

{

next = null;

element = null;

}

/**

* Creates a node storing the specified element.

* @param elem element to be stored

*/

public LinearNode(T elem)

{

next = null;

element = elem;

}

/**

* Returns the node that follows this one.

* @return reference to next node

*/

public LinearNode getNext()

{

return next;

}

/**

* Sets the node that follows this one.

* @param node node to follow this one

*/

public void setNext(LinearNode node)

{

next = node;

}

/**

* Returns the element stored in this node.

* @return element stored at the node

*/

public T getElement()

{

return element;

}

/**

* Sets the element stored in this node.

* @param elem element to be stored at this node

*/

public void setElement(T elem)

{

element = elem;

}

}

############################################### EmptyCollectionException Class ###############################################

/**

* Represents the situation in which a collection is empty.

*

* @author Java Foundations

* @version 4.0

*/

public class EmptyCollectionException extends RuntimeException

{

/**

* Quickfix for possible errors

*/

private static final long serialVersionUID = 1L;

/**

* Sets up this exception with an appropriate message.

* @param collection the name of the collection

*/

public EmptyCollectionException(String collection)

{

super("The " + collection + " is empty.");

}

}




0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for LinkedStack.java and Test.java (driver). Other files are unchanged. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

//LinkedStack.java (modified to be a dropout stack. you may use

//a different name for the class if you want)

public class LinkedStack<T> implements StackADT<T> {

      private int count, maxCapacity;

      private LinearNode<T> top;

      /**

      *

      * Creates an empty stack.

      */

      public LinkedStack(int size) {

            count = 0;

            top = null;

            //assuming max size > 0

            maxCapacity = size;

      }

      /**

      *

      * Adds the specified element to the top of this stack.

      *

      * @param element

      *            element to be pushed on stack

      */

      public void push(T element) {

            LinearNode<T> temp = new LinearNode(element);

            temp.setNext(top);

            top = temp;

            count++;

            //checking if count exceeded max capacity

            if (count > maxCapacity) {

                  //if max capacity is 1, removing next of top node

                  if (maxCapacity == 1) {

                        top.setNext(null);

                        //updating count and returning

                        count--;

                        return;

                  }

                  //otherwise taking reference to top

                  temp = top;

                  //looping until top is the node before bottom node

                  while (temp.getNext().getNext() != null) {

                        //advancing temp

                        temp = temp.getNext();

                  }

                  //removing bottom and updating count

                  temp.setNext(null);

                  count--;

            }

      }

      /**

      *

      * Removes the element at the top of this stack and returns a

      *

      * reference to it.

      *

      * @return element from top of stack

      *

      * @throws EmptyCollectionException

      *             if the stack is empty

      */

      public T pop() throws EmptyCollectionException {

            if (isEmpty())

                  throw new EmptyCollectionException("stack");

            T result = top.getElement();

            top = top.getNext();

            count--;

            return result;

      }

      /**

      *

      * Returns a reference to the element at the top of this stack.

      *

      * The element is not removed from the stack.

      *

      * @return element on top of stack

      *

      * @throws EmptyCollectionException

      *             if the stack is empty

      */

      public T peek() throws EmptyCollectionException {

            if (isEmpty())

                  throw new EmptyCollectionException("stack");

            return top.getElement();

      }

      /**

      *

      * Returns true if this stack is empty and false otherwise.

      *

      * @return true if stack is empty

      */

      public boolean isEmpty() {

            return count == 0;

      }

      /**

      *

      * Returns the number of elements in this stack.

      *

      * @return number of elements in the stack

      */

      public int size() {

            return count;

      }

      /**

      *

      * Returns a string representation of this stack.

      *

      * @return string representation of the stack

      */

      public String toString() {

            //appending data of each node from top to bottom into a String

            String str = "top [";

            for (LinearNode<T> node = top; node != null; node = node.getNext()) {

                  str += node.getElement();

                  if (node.getNext() != null) {

                        str += ", ";

                  }

            }

            str += "] bottom";

            return str;

      }

      @Override

      public T getBottom() {

            if (isEmpty())

                  throw new EmptyCollectionException("stack");

            LinearNode<T> temp = top;

            //looping until temp is the last/bottom node

            while (temp.getNext() != null) {

                  temp = temp.getNext();

            }

            //returning data of temp

            return temp.getElement();

      }

}

//Test.java (driver program for testing)

public class Test {

      public static void main(String[] args) {

            // creating an int LinkedStack of max size 5

            LinkedStack<Integer> iStack = new LinkedStack<Integer>(5);

            System.out.println("Adding numbers from 1 to 10 to"

                        + " an integer stack of max size 5");

            // adding numbers from 1 to 10. the first 5 numbers will be truncated as

            // max size is 5

            for (int i = 1; i <= 10; i++) {

                  iStack.push(i);

                  //displaying stack after each addition

                  System.out.println(iStack);

            }

            System.out.println("\nPopping elements until empty");

            //looping and removing each element until stack is empty

            while (!iStack.isEmpty()) {

                  System.out.println(iStack.pop() + " is removed");

                  System.out.println(iStack);

            }

           

            //now testing the stack using String as type

            LinkedStack<String> sStack = new LinkedStack<String>(3);

            sStack.push("Adam");

            sStack.push("Beric");

            sStack.push("Cait");

            System.out.println("\nString linked stack of max size 3: " + sStack);

            sStack.push("Dave");

            System.out.println("After adding 'Dave': " + sStack);

            sStack.push("Emily");

            System.out.println("After adding 'Emily': " + sStack);

            System.out.println("Top: " + sStack.peek());

            System.out.println("Bottom: " + sStack.getBottom());

      }

}

/*OUTPUT*/

Adding numbers from 1 to 10 to an integer stack of max size 5

top [1] bottom

top [2, 1] bottom

top [3, 2, 1] bottom

top [4, 3, 2, 1] bottom

top [5, 4, 3, 2, 1] bottom

top [6, 5, 4, 3, 2] bottom

top [7, 6, 5, 4, 3] bottom

top [8, 7, 6, 5, 4] bottom

top [9, 8, 7, 6, 5] bottom

top [10, 9, 8, 7, 6] bottom

Popping elements until empty

10 is removed

top [9, 8, 7, 6] bottom

9 is removed

top [8, 7, 6] bottom

8 is removed

top [7, 6] bottom

7 is removed

top [6] bottom

6 is removed

top [] bottom

String linked stack of max size 3: top [Cait, Beric, Adam] bottom

After adding 'Dave': top [Dave, Cait, Beric] bottom

After adding 'Emily': top [Emily, Dave, Cait] bottom

Top: Emily

Bottom: Cait

Add a comment
Know the answer?
Add Answer to:
There is a data structure called a drop-out stack that behaves like a stack in every...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In addition to the base files, three additional files are attached: EmptyCollectionException.java, LinearNode.java, and StackADT.java. These...

    In addition to the base files, three additional files are attached: EmptyCollectionException.java, LinearNode.java, and StackADT.java. These files will need to be added to your Java project. They provide data structure functionality that you will build over. It is suggested that you test if these files have been properly added to your project by confirming that Base_A05Q1.java compiles correctly. Complete the implementation of the ArrayStack class. Specifically, complete the implementations of the isEmpty, size, and toString methods. See Base_A05Q1.java for a...

  • Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of...

    Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of the peek, isEmpty, size, and toString methods. See Base_A06Q1.java for a starting place and a description of these methods. Here is the base given: /** * Write a description of the program here. * * @author Lewis et al., (your name) * @version (program version) */ import java.util.Iterator; public class Base_A06Q1 { /** * Program entry point for stack testing. * @param args Argument...

  • In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> {...

    In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> { /** Adds one element to the top of this stack. * @param element element to be pushed onto stack */ public void push (T element);    /** Removes and returns the top element from this stack. * @return T element removed from the top of the stack */ public T pop(); /** Returns without removing the top element of this stack. * @return T...

  • Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...

    Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix)    {        LinkedStack stack2 = new LinkedStack();        int val1;        int val2;        int result;        for(int i = 0; i < postFix.length(); i++)        {            char m = postFix.charAt(i);            if(Character.isDigit(m))            {                stack2.push(m);            }            else            {               ...

  • Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns...

    Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns a value of primitive type int equal to the number of items on the stack. The method signature for sizeIS is public int sizeIs() a.) Write the code for sizeIs for the ArrayStack class b.) Write the code for sizeIs for the LinkedStack class (do not add any instance variables to the class; each time sizeIs is called you must "walk" through the stack...

  • I just need a java mehod that follows the Javadocs Implented using an arraylist. public class...

    I just need a java mehod that follows the Javadocs Implented using an arraylist. public class WorkAheadQueue<T> implements WorkAheadQueueADT<T> {     private LinearNode<T> front;     private LinearNode<T> back;     private int numNodes;     private ArrayList<LinearNode<T>> frontFive; Removes and returns the element that is at place x in the queue. Precondition: x must be less than 5, x must be less than size * Note: indexing from 0: 0-front element, I =-second element, etc. eparam x the passed in index of...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • Java - data structures Suppose that in the array-based stack, the array doubles in size after...

    Java - data structures Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations. Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows: The first new method checks whether we should reduce the...

  • NO ONE HAS PROVIDED THE CORRECT CODE TO PROVIDE THE GIVEN OUTPUT. PLEASE PROVIDE CODE THAT...

    NO ONE HAS PROVIDED THE CORRECT CODE TO PROVIDE THE GIVEN OUTPUT. PLEASE PROVIDE CODE THAT WOULD CAUSE THE HW1.java TO PRINT THE RIGHT DATA.!!! The LinkedList class implements both the List interface and the Stack interface, but several methods (listed below) are missing bodies. Write the code so it works correctly. You should submit one file, LinkedList.java. Do not change the interfaces. Do not change the public method headers. Do not rename the LinkedList class. None of your methods...

  • Using Java coding, complete the following: This program should implement a LinkedList data structure to handle...

    Using Java coding, complete the following: This program should implement a LinkedList data structure to handle the management of student records. It will need to be able to store any number of students, using a Linked List. LinearNode.java can be used to aid creating this program Student should be a class defined with the following:    • String name    • int year    • A linked list of college classes (college classes are represented using strings)    • An...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT