Question

In: Computer Science

Write a java code for LinkedStack implementation and the code is: public final class LinkedStack<T> implements...

Write a java code for LinkedStack implementation and the code is:

public final class LinkedStack<T> implements StackInterface<T> {    private Node topNode; // References the first node in the chain       public LinkedStack()    {        topNode = null;    } // end default constructor       public void push(T newEntry)    { topNode = new Node(newEntry, topNode); //       Node newNode = new Node(newEntry, topNode); //       topNode = newNode;    } // end push    public T peek()    {        if (isEmpty())            throw new EmptyStackException();        else return topNode.getData();    } // end peek    public T pop()    {    T top = peek(); // Might throw EmptyStackException    assert (topNode != null); topNode = topNode.getNextNode();    return top;    } // end pop /* // Question 1, Chapter 6: Does not call peek    public T pop()    { if (isEmpty()) throw new EmptyStackException(); else        { assert (topNode != null);            top = topNode.getData();            topNode = topNode.getNextNode();        } // end if               return top;    } // end pop */          public boolean isEmpty()    {        return topNode == null;    } // end isEmpty       public void clear()    {        topNode = null; // Causes deallocation of nodes in the chain    } // end clear    private class Node    { private T data; // Entry in stack private Node next; // Link to next node private Node(T dataPortion) { this(dataPortion, null); } // end constructor private Node(T dataPortion, Node linkPortion) { data = dataPortion; next = linkPortion;   } // end constructor private T getData() { return data; } // end getData private void setData(T newData) { data = newData; } // end setData private Node getNextNode() { return next; } // end getNextNode private void setNextNode(Node nextNode) { next = nextNode; } // end setNextNode    } // end Node } // end LinkedStack

Write the method of type T in this class to pop’s the bottom/last element in the stack if stack is not empty otherwise it returns null. and another method of type boolean to removes the first element in the stack to the last element in the stack. If successful return true otherwise return false

Solutions

Expert Solution

Here is the completed code for this problem. Added codes for popBottom() method and moveFirstToLast() method. Change method names as you wish. 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

public final class LinkedStack<T> implements StackInterface<T> {

      private Node topNode; // References the first node in the chain

      public LinkedStack() {

            topNode = null;

      }

      // end default constructor

      public void push(T newEntry) {

            topNode = new Node(newEntry, topNode);

            // Node newNode = new Node(newEntry, topNode);

            // topNode = newNode;

      } // end push

      public T peek() {

            if (isEmpty())

                  throw new EmptyStackException();

            else

                  return topNode.getData();

      } // end peek

      public T pop() {

            T top = peek(); // Might throw EmptyStackException

            assert (topNode != null);

            topNode = topNode.getNextNode();

            return top;

      } // end pop

      /*

      * // Question 1, Chapter 6: Does not call peek public T pop() { if

      * (isEmpty()) throw new EmptyStackException(); else { assert (topNode !=

      * null); top = topNode.getData(); topNode = topNode.getNextNode(); } // end

      * if return top; } // end pop

      */

      public boolean isEmpty() {

            return topNode == null;

      } // end isEmpty

      public void clear() {

            topNode = null; // Causes deallocation of nodes in the chain

      } // end clear

      // method to pop and return the bottom most element

      public T popBottom() {

            // if stack is empty, returning false

            if (isEmpty()) {

                  return null;

            }

            // if stack has only one element, setting top node to null, and

            // returning the removed value

            if (topNode.getNextNode() == null) {

                  T data = topNode.getData();

                  topNode = null;

                  return data;

            }

            // otherwise taking reference to first two nodes

            Node prev = topNode;

            Node next = topNode.getNextNode();

            // looping until next is the last node

            while (next.getNextNode() != null) {

                  // advancing nodes

                  prev = next;

                  next = next.getNextNode();

            }

            // now we simply removing next node (the last node) by setting null as

            // next node of prev

            T data = next.getData();

            prev.setNextNode(null);

            return data; // returning removed data

      }

      // method to move first element (top) to the last (bottom)

      public boolean moveFirstToLast() {

            // returning false if stack is empty

            if (isEmpty()) {

                  return false;

            }

            // returning true if stack has only one element (we dont have to do

            // anything in that case, you may return false if you prefer that)

            if (topNode.getNextNode() == null) {

                  return true;

            }

            // popping top value

            T data = pop();

            // and finding the last node starting from new topNode

            Node n = topNode;

            while (n.getNextNode() != null) {

                  n = n.getNextNode();

            }

            // adding the removed value as the next of current last node

            n.setNextNode(new Node(data));

            return true; // success

      }

      private class Node {

            private T data; // Entry in stack

            private Node next; // Link to next node

            private Node(T dataPortion) {

                  this(dataPortion, null);

            } // end constructor

            private Node(T dataPortion, Node linkPortion) {

                  data = dataPortion;

                  next = linkPortion;

            } // end constructor

            private T getData() {

                  return data;

            } // end getData

            private void setData(T newData) {

                  data = newData;

            } // end setData

            private Node getNextNode() {

                  return next;

            } // end getNextNode

            private void setNextNode(Node nextNode) {

                  next = nextNode;

            } // end setNextNode

      } // end Node

} // end LinkedStack


Related Solutions

Using this BubbleSort implementation in Java: public class BubbleSort<T extends Comparable<T>> {    private static <T...
Using this BubbleSort implementation in Java: public class BubbleSort<T extends Comparable<T>> {    private static <T extends Comparable<T>>    void swap(T[] data, int index1, int index2)    {       T temp = data[index1];       data[index1] = data[index2];       data[index2] = temp;    }    public void sort(T[] data)    {       int position, scan;       for (position = data.length - 1; position >= 0; position--)       {          for (scan = 0; scan <= position - 1; scan++)          {...
In Java, please write a tester code. Here's my code: public class Bicycle {     public...
In Java, please write a tester code. Here's my code: public class Bicycle {     public int cadence; public int gear;   public int speed;     public Bicycle(int startCadence, int startSpeed, int startGear) {         gear = startGear;   cadence = startCadence; speed = startSpeed;     }     public void setCadence(int newValue) {         cadence = newValue;     }     public void setGear(int newValue) {         gear = newValue;     }     public void applyBrake(int decrement) {         speed -= decrement;    ...
Please add comments to this code! JAVA code: import java.util.ArrayList; public class ShoppingCart { private final...
Please add comments to this code! JAVA code: import java.util.ArrayList; public class ShoppingCart { private final ArrayList<ItemOrder> itemOrder;    private double total = 0;    private double discount = 0;    ShoppingCart() {        itemOrder = new ArrayList<>();        total = 0;    }    public void setDiscount(boolean selected) {        if (selected) {            discount = total * .1;        }    }    public double getTotal() {        total = 0;        itemOrder.forEach((order) -> {            total +=...
COMPLETE JAVA CODE: public final class Vector2 {       // NOTE:    Before you get...
COMPLETE JAVA CODE: public final class Vector2 {       // NOTE:    Before you get started with the constructors, implement the class variables and    // =====   the accessor methods (getX,getY). The tester for the constructors relies on these    //           methods being implemented. After this, move ahead with the constructors          // class variables here       COMPLETE JAVA CODE: /** * Creates the vector <code>(0.0, 0.0)</code>. */ public Vector2() {       COMPLETE...
Author code /** * LinkedList class implements a doubly-linked list. */ public class MyLinkedList<AnyType> implements Iterable<AnyType>...
Author code /** * LinkedList class implements a doubly-linked list. */ public class MyLinkedList<AnyType> implements Iterable<AnyType> { /** * Construct an empty LinkedList. */ public MyLinkedList( ) { doClear( ); } private void clear( ) { doClear( ); } /** * Change the size of this collection to zero. */ public void doClear( ) { beginMarker = new Node<>( null, null, null ); endMarker = new Node<>( null, beginMarker, null ); beginMarker.next = endMarker; theSize = 0; modCount++; } /**...
In java design and code a class named comparableTriangle that extends Triangle and implements Comparable. Implement...
In java design and code a class named comparableTriangle that extends Triangle and implements Comparable. Implement the compareTo method to compare the triangles on the basis of similarity. Draw the UML diagram for your classes. Write a Driver class (class which instantiates the comparableTriangle objects) to determine if two instances of ComparableTriangle objects are similar (sample output below). It should prompt the user to enter the 3 sides of each triangle and then display whether or not the are similar...
1. Consider the following code: public class Widget implements Serializable { private int x; public void...
1. Consider the following code: public class Widget implements Serializable { private int x; public void setX( int d ) { x = d; } public int getX() { return x; } writeObject( Object o ) { o.writeInt(x); } } Which of the following statements is true? I. The Widget class is not serializable because no constructor is defined. II. The Widget class is not serializable because the implementation of writeObject() is not needed. III. The code will not compile...
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....
I needv pseudocode and a flowchart for the following java code public class AcmePay { public...
I needv pseudocode and a flowchart for the following java code public class AcmePay { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); int hours, shift, retirement = 0; do { System.out.print("Enter the number of hours worked (>0): "); hours = scanner.nextInt(); } while (hours <= 0); do { System.out.print("Enter shift [1 2 or 3]: "); shift = scanner.nextInt(); } while (shift < 1 || shift > 3); if (shift == 2 || shift ==...
Java programming. Write a public Java class called DecimalTimer with public method displayTimer, that prints a...
Java programming. Write a public Java class called DecimalTimer with public method displayTimer, that prints a counter and then increments the number of seconds. The counter will start at 00:00 and each time the number of seconds reaches 60, minutes will be incremented. You will not need to implement hours or a sleep function, but if minutes or seconds is less than 10, make sure a leading zero is put to the left of the number. For example, 60 seconds:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT