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

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;    ...
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++)          {...
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 +=...
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...
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:...
Write a Java program that implements a song database. The SongsDatabase class keeps tracks of song...
Write a Java program that implements a song database. The SongsDatabase class keeps tracks of song titles by classifying them according to genre (e.g., Pop, Rock, etc.). The class uses a HashMap to map a genre with a set of songs that belong to such a genre. The set of songs will be represented using a HashSet. Your driver output should sufficiently prove that your code properly implements the code below. public class SongsDatabase { private Map<String, Set<String>> genreMap =...
Code in python: Write a class that implements a struct. In your struct store Student information...
Code in python: Write a class that implements a struct. In your struct store Student information such as name, netid, and gpa. Write a function that can access a student in a list of 5 structs by netid and print their name and gpa. Show that your function works by calling it.
Please solve this problem in java. (simple linked list) public class MyLinkedList implements MiniList{ /* Private...
Please solve this problem in java. (simple linked list) public class MyLinkedList implements MiniList{ /* Private member variables that you need to declare: ** The head pointer ** The tail pointer */    private Node head;    private Node tail;       public class Node { // declare member variables (data and next)    Integer data;    Node next; // finish these constructors    public Node(int data, Node next) {               this.data=data;        this.next=next;    }...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT