Question

In: Computer Science

IN JAVA: Repeat Exercise 28, but add the methods to the LinkedStack class. Add the following...

IN JAVA:

Repeat Exercise 28, but add the methods to the LinkedStack class.

Add the following methods to the LinkedStacked class, and create a test driver for each to show that they work correctly. In order to practice your array related coding skills, code each of these methods by accessing the internal variables of the LinkedStacked, not by calling the previously defined public methods of the class.

- String toString()—creates and returns a string that correctly represents the current stack. Such a method could prove useful for testing and debugging the class and for testing and debugging applications that use the class. Assume each stacked element already provided its own reasonable toString method.

- intsize()—returnsacountofhowmanyitemsarecurrentlyonthestack.Do not add any instance variables to the LinkStacked class in order to implement this method.

- void popSome(int count)—removes the top count elements from the stack; throws StackUnderflowException if there are less than count elements on the stack .

- booleanswapStart()—if there are less than two elements on the stack returns false; otherwise it reverses the order of the top two elements on the stack and returns true.

- T poptop( )—the “classic” pop operation, if the stack is empty it throws StackUnderflowException; otherwise it both removes and returns the top element of the stack.

package ch02.stacks;

import support.LLNode;

public class LinkedStack implements StackInterface
{
protected LLNode top; // reference to the top of this stack

public LinkedStack()
{
top = null;
}

public void push(T element)
// Places element at the top of this stack.
{
LLNode newNode = new LLNode(element);
newNode.setLink(top);
top = newNode;
}

public void pop()
// Throws StackUnderflowException if this stack is empty,
// otherwise removes top element from this stack.
{
if (isEmpty())
throw new StackUnderflowException("Pop attempted on an empty stack.");
else
top = top.getLink();
}

public T top()
// Throws StackUnderflowException if this stack is empty,
// otherwise returns top element of this stack.
{
if (isEmpty())
throw new StackUnderflowException("Top attempted on an empty stack.");
else
return top.getInfo();
}

public boolean isEmpty()
// Returns true if this stack is empty, otherwise returns false.
{
return (top == null);
}

public boolean isFull()
// Returns false - a linked stack is never full
{
return false;
}

}

Solutions

Expert Solution

package ch02.stacks;

import support.LLNode;

public class LinkedStack implements StackInterface
{
protected LLNode top; // reference to the top of this stack

public LinkedStack()
{
top = null;
}

public void push(T element)
// Places element at the top of this stack.
{
LLNode newNode = new LLNode(element);
newNode.setLink(top);
top = newNode;
}

public void pop()
// Throws StackUnderflowException if this stack is empty,
// otherwise removes top element from this stack.
{
if (isEmpty())
throw new StackUnderflowException("Pop attempted on an empty stack.");
else
top = top.getLink();
}

public T top()
// Throws StackUnderflowException if this stack is empty,
// otherwise returns top element of this stack.
{
if (isEmpty())
throw new StackUnderflowException("Top attempted on an empty stack.");
else
return top.getInfo();
}

public boolean isEmpty()
// Returns true if this stack is empty, otherwise returns false.
{
return (top == null);
}

public boolean isFull()
// Returns false - a linked stack is never full
{
return false;
}

public T poptop()
//if the stack is empty it throws StackUnderflowException;
//otherwise it both removes and returns the top element of the stack
{
   if(isEmpty())
       throw new StackUnderflowException("Pop attempted on an empty stack.");
   T info = top.getInfo();
   top = top.getLink();
   return info;
}

public int size()
//returns a count of how many items are currently on the stack
{
   LLNode tmp = top;
   int count=0;
   while(tmp != null)
   {
       count++;
       tmp = tmp.getLink();
   }
   return count;
}

public boolean booleanswapStart()
//if there are less than two elements on the stack returns false;
//otherwise it reverses the order of the top two elements on the stack and returns true
{
   if(size() < 2)
       return false;
      
   T p = top.getInfo();
   top = top.getLink();
  
   T q = top.getInfo();
   top = top.getLink();

   LLNode newNode = new LLNode(p);
   newNode.setLink(top);
   top = newNode;
  
   newNode = new LLNode(q);
   newNode.setLink(top);
   top = newNode;

   return true;
}

public void popSome(int count)
//removes the top count elements from the stack;
//throws StackUnderflowException if there are less than count elements on the stack .
{
   if(size()<count)
       throw new StackUnderflowException("Less than count elements on the stack.");
   for(int i=0; i<count; i++)
   {
       top = top.getLink();
   }
}

public String toString()
//creates and returns a string that correctly represents the current stack.
{
   String s = "";
   LLNode tmp = top;
   while(tmp != null)
   {
       s = s + tmp.getInfo() + " ";
       tmp = tmp.getLink();
   }
   return s;
}

}

//Driver class
class Driver
{
   //main method
   public static void main (String[] args) throws StackUnderflowException
   {
       //create a stack of Integers
       LinkedStack<Integer> stack = new LinkedStack<Integer>();
      
       stack.push(10);
       stack.push(20);
       stack.push(30);
       stack.push(40);
       stack.push(50);
      
       //print the stack after push operation
       System.out.println (stack);
      
       boolean fg = stack.booleanswapStart();
      
       //print the stack after booleanswapStart operation
       System.out.println (stack);
      
       //print the size of the stack
       System.out.println ("Size of the Stack = " + stack.size());
      
       stack.popSome(2);
      
       //print the stack after popSome operation
       System.out.println (stack);
      
       System.out.println ("Popped " + stack.poptop());
       System.out.println ("Popped " + stack.poptop());
       System.out.println ("Popped " + stack.poptop());
      
       //print the size of the stack
       System.out.println ("Size of the Stack = " + stack.size());
      
   }
}

Note: I have added the methods to the LinkedStacked class and write a test driver class. But since you have not add the full code I have not able to run it.  Whether you face any problem or need any modification then share with me in the comment section, I'll happy to help you.


Related Solutions

28. Add the following methods to the ArrayBoundedStack class, and create a test driver for each...
28. Add the following methods to the ArrayBoundedStack class, and create a test driver for each to show that they work correctly. In order to practice your array related coding skills, code each of these methods by accessing the internal variables of the ArrayBoundedStack, not by calling the previously defined public methods of the class. a. String toString()—creates and returns a string that correctly represents the current stack. Such a method could prove useful for testing and debugging the class...
Code in Java Given the LinkedList class that is shown below Add the following methods: add(String...
Code in Java Given the LinkedList class that is shown below Add the following methods: add(String new_word): Adds a linkedlist item at the end of the linkedlist print(): Prints all the words inside of the linkedlist length(): Returns an int with the length of items in the linkedlist remove(int index): removes item at specified index itemAt(int index): returns LinkedList item at the index in the linkedlist public class MyLinkedList { private String name; private MyLinkedList next; public MyLinkedList(String n) {...
java code Add the following methods to the LinkedQueue class, and create a test driver for...
java code Add the following methods to the LinkedQueue class, and create a test driver for each to show that they work correctly. In order to practice your linked list cod- ing skills, code each of these methods by accessing the internal variables of the LinkedQueue, not by calling the previously de?ined public methods of the class. String toString() creates and returns a string that correctly represents the current queue. Such a method could prove useful for testing and debugging...
THIS QUESTION IS BASED UPON JAVA PROGRAMMING. Exercise 1 In this exercise, you will add a...
THIS QUESTION IS BASED UPON JAVA PROGRAMMING. Exercise 1 In this exercise, you will add a method swapNodes to SinglyLinkedList class. This method should swap two nodes node1 and node2 (and not just their contents) given references only to node1 and node2. The new method should check if node1 and node2 are the same nodes, etc. Write the main method to test the swapNodes method. Hint: You may need to traverse the list. Exercise 2 In this exercise, you will...
Use Java programming to implement the following: Implement the following methods in the UnorderedList class for...
Use Java programming to implement the following: Implement the following methods in the UnorderedList class for managing a singly linked list that cannot contain duplicates. Default constructor Create an empty list i.e., head is null. boolean insert(int data) Insert the given data into the end of the list. If the insertion is successful, the function returns true; otherwise, returns false. boolean delete(int data) Delete the node that contains the given data from the list. If the deletion is successful, the...
Add code (see below for details) to the methods "set" and "get" in the following class,...
Add code (see below for details) to the methods "set" and "get" in the following class, ArrayTen.java, so that these two methods catch the exception java.lang.ArrayIndexOutOfBoundsException if an illegal index is used, and in turn throw java.lang.IndexOutOfBoundsException instead. Modify the "main" method to catch java.lang.IndexOutOfBoundsException and, when such an exception is caught, print the exception as well as the stack trace. public class ArrayTen { private String myData[] = new String[10]; public void set(int index, String value) { myData[index] =...
Add a generic Node class to the Java project. In the class Declare the fields using...
Add a generic Node class to the Java project. In the class Declare the fields using the generic type parameter, follow the book specification Define the accessor method getLink( ) Define the constructor, follow the book implementation Note: at the definition the name of the constructor is Node, however every time you use it as a type must postfix the generic type like Node<T> Define the addNodeAfter( ) method as explained in the PP presentation, use the generic type as...
JAVA Add static methods largest and smallest to the Measurable interface. The methods should return the...
JAVA Add static methods largest and smallest to the Measurable interface. The methods should return the object with the largest or smallest measure from an array of Measurable objects.
write program that develop a Java class Dictionary to support the following public methods of an...
write program that develop a Java class Dictionary to support the following public methods of an abstract data type: public class Dictionary { // insert a (key, value) pair into the Dictionary, key value must be unique, the value is associated with the key; only the last value inserted for a key will be kept public void insert(String key, String value); // return the value associated with the key value public String lookup(String key); // delete the (key, value) pair...
Java Language -Create a project and a class with a main method, TestCollectors. -Add new class,...
Java Language -Create a project and a class with a main method, TestCollectors. -Add new class, Collector, which has an int instance variable collected, to keep track of how many of something they collected, another available, for how many of that thing exist, and a boolean completist, which is true if we want to collect every item available, or false if we don't care about having the complete set. -Add a method addToCollection. In this method, add one to collected...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT