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...
Write the following Java code into Pseudocode import java.util.*; public class Main { // Searching module...
Write the following Java code into Pseudocode import java.util.*; public class Main { // Searching module public static void score_search(int s,int score[]) { // Initialise flag as 0 int flag=0; // Looping till the end of the array for(int j=0;j<10;j++) { // If the element is found in the array if(s==score[j]) { // Update flag to 1 flag=1; } } // In case flag is 1 element is found if(flag==1) { System.out.println("golf score found"); } // // In case flag...
JAVA Write a class for a Stack of characters using a linked list implementation. Write a...
JAVA Write a class for a Stack of characters using a linked list implementation. Write a class for a Queue of characters using a linked list implementation. Write a class for a Queue of integers using a circular array implementation.
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....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT