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

Can you fix my code and remove the errors in java language. public class LinkedStack<T> implements...
Can you fix my code and remove the errors in java language. public class LinkedStack<T> implements Stack<T> { private Node<T> top; private int numElements = 0; public int size() { return (numElements); } public boolean isEmpty() { return (top == null); } public T top() throws StackException { if (isEmpty()) throw new StackException("Stack is empty."); return top.info; } public T pop() throws StackException { Node<T> temp; if (isEmpty()) throw new StackException("Stack underflow."); temp = top; top = top.getLink(); return temp.getInfo();...
FOR JAVA: Need to write a code for the implementation of this public static method: findLongestPalindrome...
FOR JAVA: Need to write a code for the implementation of this public static method: findLongestPalindrome takes a Scanner scn as its parameter and returns a String. It returns the longest token from scn that is a palindrome (if one exists) or the empty string (otherwise). (Implementation note: You'll find your isPalindrome method helpful here. This method calls for an optimization loop.)
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++; } /**...
Convert the Queue to Generic implementation: public class MyQueueImpl implements MyQueue {    private int capacity;...
Convert the Queue to Generic implementation: public class MyQueueImpl implements MyQueue {    private int capacity;    private int front;    private int rear;    private int[] arr;    public MyQueueImpl(int capacity){        this.capacity = capacity;        this.front = 0;        this.rear = -1;        this.arr = new int[this.capacity];    }    @Override    public boolean enQueue(int v) {                  if(this.rear == this.capacity - 1) {                //Perform shift   ...
In java, write a class that tests the following code. Add screen shots as well. public...
In java, write a class that tests the following code. Add screen shots as well. public class DoubleStack<E> {    private E[] elements;    private int top1, top2;    private static int DEFAULT_SIZE = 10;       public DoubleStack() {        elements = (E[])new Object[DEFAULT_SIZE];        top1 = 0;        top2 = elements.length - 1;    }       public boolean isFull(int stack) {        if(top2 == top1 + 1)            return true;   ...
WRITE THIS JAVA CODE IN PSEUDOCODE!! import java.util.Scanner; public class License { public static void main(String[]...
WRITE THIS JAVA CODE IN PSEUDOCODE!! import java.util.Scanner; public class License { public static void main(String[] args) { char correctAnswers[] = {'B', 'D', 'A', 'A', 'C', 'A', 'B', 'A', 'C', 'D', 'B', 'C', 'D', 'A', 'D', 'C', 'C', 'B', 'D', 'A'}; char userAnswers[] = new char[correctAnswers.length]; Scanner scanner = new Scanner(System.in); for (int i = 0; i < userAnswers.length; i++) { String answer = ""; System.out.printf("Question #%d. Enter your answer( A, B, C or D): ", i + 1); do...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT