Menu

(Solved) : Part Used Singly Linked List Node Knows Next Node List Previous Doubly Linked List Nodes K Q27825212 . . .

In Part I we used a Singly Linked List, where each node knowsthe next node in the list, but not the previous. With a doublylinked list, nodes will now know both the previous and next nodes.This provides some efficiencies for certain types of operations,like for reversing a list. For this part, you should find threesource files. Note that ColorListApp is a JavaFXapp that you can run and will demonstrate use ofGenericDoublyLinkedList, which is where you willwrite your code. Look through all three classes and be sure tocarefully read the documentation.

With a doubly linked list, you must always be careful toproperly update the next & prev node variables after eachoperation on the list.

In addition to being a doubly linked list, in this part you willbe manipulating a generic list, just as we discussed in lecture.Your list will be able to store any type of objects. TheColorListApp class provides one example,demonstrating the use of your class for storing and manipulatingColor objects. When you feel that your methods are properlydefined, try playing around with the ColorListApp application.

NOTE: you should write your own little driverclass (a class with a main method) for testing your methodsindependently of ColorListApp, which has lots of stuff that mayconfuse you. Create a main method and build your list and print thecontents to verify if your method are working properly.

YOUR FOUR METHODS, ALL FOR THE GenericDoublyLinkedListCLASS

Define the clear method such that it whencalled it completely empties the list of all nodes.

Define the moveFrontToLast method such that ittakes the first node in the list and moves it to the end of thelist, leaving the rest of the list as it was.

Define the moveLastToFront method such that ittakes the last node in the list and moves it to the front of thelist, leaving the rest of the list as it was.

Define the reverse method such that it simplyreverses the order of the nodes in the list. So, what was first isnow last, what was last is now first, etc. A list that wasoriginally ABCDE would be EDCBA after being reversed.

Here is a code.

package part_two_color_animation;

import java.util.Iterator;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;

/**
* ColorCanvas.java
*
* DO NOT CHANGE THIS FILE
*
* This class does the rendering of the list of Colors in alist.
*
*/
public class ColorCanvas extends Canvas {

    // THIS IS THE LIST WE’LL BE DRAWING
    GenericDoublyLinkedList<Color>colorList;
   
    // THIS APP WILL MONITOR THESE FORRENDERING
    // THE FRAME RATE
    BooleanProperty keepAnimatingProperty;
    IntegerProperty fpsProperty;

    // THESE ARE ALL THE DRAWING CONSTANTSFOR
    // SIZING AND LOCATING THINGS
    final int TEXT_X_OFFSET = 20;
    final int TEXT_Y_OFFSET = 5;
    final int RECT_WIDTH = 40;
    final int RECT_HEIGHT = 40;
    final int RECT_X_OFFSET = 0;
    final int RECT_Y_OFFSET = 0;
    final int NODES_PER_ROW = 32;
    final int MAX_NODES = 720;
    final int FPS_X = 20;
    final int FPS_Y = 20;
    final int NODES_PER_COLUMN = MAX_NODES /NODES_PER_ROW;
    Font nodeFont = Font.font(“Helvetica”,FontWeight.NORMAL, FontPosture.REGULAR, 16);

    /**
     * Constructor, it initializes everythingthis canvas
     * needs to draw the list of colors.
     */
    public ColorCanvas( BooleanPropertyinitKeepAnimatingProperty,
                       IntegerProperty initFpsProperty,
                       GenericDoublyLinkedList<Color> initColorList) {
        keepAnimatingProperty =initKeepAnimatingProperty;
        fpsProperty =initFpsProperty;
        colorList =initColorList;
    }

    /**
     * This function clears the canvas and thendoes
     * the rendering, this is to be called eachtime
     * the list is changed.
     */
    public void repaint() {
        // THIS DOES THE ACTUALRENDERING
        GraphicsContext gC =getGraphicsContext2D();
       gC.setFont(nodeFont);

        // WHAT ARE THE PANELDIMENSIONS
        int canvasWidth = (int)getWidth();
        int canvasHeight = (int)getHeight();

        // CLEAR OUT WHAT WEDREW PREVIOUSLY
        gC.clearRect(0, 0,canvasWidth, canvasHeight);

        // CALCULATE THE SIZEOF EVERYTHING WE NEED TO DRAW
        int totalWidth =(NODES_PER_ROW * RECT_WIDTH) + ((NODES_PER_ROW – 1) *RECT_X_OFFSET);
        int totalHeight =((NODES_PER_COLUMN + 2) * RECT_HEIGHT) + ((NODES_PER_COLUMN + 1) *RECT_Y_OFFSET);

        // FIRST DRAW THEFRAME RATE
        gC.strokeText(“FramesPer Second: ” + fpsProperty.getValue(), FPS_X, FPS_Y);
       
        // CALCULATE THE CANVASLOCATION OF THE FIRST NODE
        int rectX = (canvasWidth/ 2) – (totalWidth / 2);
        int rectY =(canvasHeight / 2) – (totalHeight / 2) + RECT_HEIGHT;

        // WE’LL USE THESE TOCALCULATE COLOR LOCATIONS
        int row;
        boolean drawingComplete= false;
        int counter = 0;
       
        // GO THROUGH ALL THECOLORS IN THE LIST ONCE
        Iterator it =colorList.listIterator();
        while (!drawingComplete){
           // CALCULATE THE ROW
           row = counter / NODES_PER_ROW;

           if (!it.hasNext()) {
               // WE JUST PASSED THE LAST NODE IN THE LIST,
               // TIME TO END THE RENDERING
               drawingComplete = true;
           } else {
               // MORE NODES TO RENDER
               Color color = (Color) it.next();
               
               // FILL A RECTANGLE WITH THIS COLOR
               gC.setFill(color);
               gC.fillRect(rectX, rectY, RECT_WIDTH, RECT_HEIGHT);
               counter++;

               // LAST NODE IN ROW
               if ((counter % NODES_PER_ROW) == 0) {
                   rectY += RECT_HEIGHT + RECT_Y_OFFSET;
               }
               // FIRST NODE IN ROW, PREV POINTS UP
               else if ((counter % NODES_PER_ROW) == 1) {
                   // NEXT IS TO THE RIGHT
                   if ((row % 2) == 0) {
                       rectX += RECT_WIDTH + RECT_X_OFFSET;
                   }
                   // NEXT IS TO THE LEFT
                   else {
                       rectX -= RECT_WIDTH + RECT_X_OFFSET;
                   }
               }
               // NEXT IS TO THE RIGHT
               else if (row % 2 == 0) {
                   rectX += RECT_WIDTH + RECT_X_OFFSET;
               }
               // NEXT IS TO THE LEFT
               else {
                   rectX -= RECT_WIDTH + RECT_X_OFFSET;
               }
           }
        }
    }
}

package part_two_color_animation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.locks.ReentrantLock;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Screen;

/**
* ColorListApp.java
*
* DO NOT CHANGE THIS FILE
*
* This class plays around with a GenericDoublyLinkedList of Colorobjects. It
* uses methods in that list class to manipulate the list and thenprovides a
* timed animation mechanism to see these manipulations inaction.
*
*/
public class ColorListApp extends Application {

    // HERE’S OUR LIST
    GenericDoublyLinkedList<Color> colorList =new GenericDoublyLinkedList();
   
    // WE’LL NEED THESE TO ANIMATE
    AnimationTimer animationThread = newAnimationTimer();
    IntegerProperty fps = newSimpleIntegerProperty(10);
    boolean restartAnimation = false;
    final int MAX_FPS = 100;
    final int MIN_FPS = 5;

    // THIS WILL MAKE SURE ONLY ONE THREAD WILLBE ACCESSING
    // SHARED DATA AT A TIME. NOTE WE WILL HAVE ATHREAD
    // FOR ANIMATION AND THE GUI ITSELF MANAGESTHREADS SO
    // THAT IT CAN DRAW THE GUI WHILE ALSO LISTENINGFOR USER INPUT
    ReentrantLock animationLock = newReentrantLock();

    // THIS IS THE WINDOW AND IT’S TOP LEVELPANE
    Stage primaryStage;
    BorderPane primaryPane = new BorderPane();
    Scene primaryScene = new Scene(primaryPane);

    // TOP TOOLBAR
    HBox topPane = new HBox();
    Button addColorButton = makeButton(“AddColor”);
    Button addAllRedsButton = makeButton(“Add AllReds”);
    Button addYellowMagentaCyanButton =makeButton(“Add Yellow-Magenta-Cyan”);
    Button addRGBButton = makeButton(“AddRed-Green-Blue”);
    Button moveFrontToLastButton = makeButton(“MoveFront to Last”);
    Button moveLastToFrontButton = makeButton(“MoveLast to Front”);
    Button reverseListButton = makeButton(“ReverseList”);
    Button removeColorsButton = makeButton(“RemoveAll Colors”);

    // THIS WILL RENDER OUR LIST
    StackPane centerPane = new StackPane();
    ColorCanvas colorCanvas = newColorCanvas(animationThread.getKeepAnimatingProperty(), fps,colorList);

    // BOTTOM TOOLBAR
    HBox bottomPane = new HBox();
    CheckBox reverseCheckBox = newCheckBox(“Reverse”);
    Button startAnimationButton = makeButton(“StartAnimation”);
    Button stopAnimationButton = makeButton(“StopAnimation”);
    Button incAnimationSpeedButton = makeButton(“IncFPS”);
    Button decAnimationSpeedButton = makeButton(“DecFPS”);

    /**
     * Default Constructor, sets up ourGUI
     */
    public void start(Stage initPrimaryStage){
        // SETUP THEWINDOW
        primaryStage =initPrimaryStage;
       primaryStage.setScene(primaryScene);
       primaryStage.setTitle(“Color List App”);

        // INIT THE GUI
        layoutGUI();

        // OPEN THEWINDOW
       primaryStage.show();
       
        // AND START OURANIMATION THREAD
       animationThread.start();
    }

    /**
     * Puts all of our GUI components in theirproper places. It also connects
     * the buttons to the button handler, whichis actually this object.
     */
    public void layoutGUI() {
        // ARRANGE THE TOPTOOLBAR
       topPane.getChildren().add(addColorButton);
       topPane.getChildren().add(addAllRedsButton);
       topPane.getChildren().add(addYellowMagentaCyanButton);
       topPane.getChildren().add(addRGBButton);
       topPane.getChildren().add(moveFrontToLastButton);
       topPane.getChildren().add(moveLastToFrontButton);
       topPane.getChildren().add(reverseListButton);
       topPane.getChildren().add(removeColorsButton);

        // THE CENTER ONLYHAS THE CANVAS
       centerPane.getChildren().add(colorCanvas);
       colorCanvas.widthProperty().bind(centerPane.widthProperty());
       colorCanvas.heightProperty().bind(centerPane.heightProperty());

        // AND THE BOTTOMTOOLBAR
       reverseCheckBox.setStyle(“-fx-font-size:14pt;-fx-padding:10px;”);
       bottomPane.getChildren().add(reverseCheckBox);
       bottomPane.getChildren().add(startAnimationButton);
       bottomPane.getChildren().add(stopAnimationButton);
       bottomPane.getChildren().add(incAnimationSpeedButton);
       bottomPane.getChildren().add(decAnimationSpeedButton);

        // MAKE THE WINDOWFIT OUR SCREEN
        Screen screen =Screen.getPrimary();
        Rectangle2D bounds =screen.getVisualBounds();
       primaryStage.setX(bounds.getMinX());
       primaryStage.setY(bounds.getMinY());
       primaryStage.setWidth(bounds.getWidth());
       primaryStage.setHeight(bounds.getHeight());

        // PUT EVERYTHING INTHE STAGE
       primaryPane.setTop(topPane);
       primaryPane.setCenter(centerPane);
       primaryPane.setBottom(bottomPane);

        // ROUTE THE EVENTSOURCES TO THEIR HANDLERS
       addColorButton.setOnAction(e -> {
           respondToButtonPress(“respondToAddColor”);
        });
       addAllRedsButton.setOnAction(e -> {
           respondToButtonPress(“respondToAddAllReds”);
        });
       addYellowMagentaCyanButton.setOnAction(e->{
           respondToButtonPress(“respondToAddYellowToMagentaToCyan”);
        });
       addRGBButton.setOnAction(e -> {
           respondToButtonPress(“respondToAddRGB”);
        });
       moveFrontToLastButton.setOnAction(e -> {
           respondToButtonPress(“respondToMoveFrontToLast”);
        });
       moveLastToFrontButton.setOnAction(e -> {
           respondToButtonPress(“respondToMoveLastToFront”);
        });
       reverseListButton.setOnAction(e -> {
           respondToButtonPress(“respondToReverseList”);
        });
       removeColorsButton.setOnAction(e -> {
           respondToButtonPress(“respondToRemoveColors”);
        });
       startAnimationButton.setOnAction(e -> {
           respondToButtonPress(“respondToStartAnimation”);
        });
       stopAnimationButton.setOnAction(e -> {
           respondToButtonPress(“respondToStopAnimation”);
        });
       incAnimationSpeedButton.setOnAction(e -> {
           respondToButtonPress(“respondToIncAnimationSpeed”);
        });
       decAnimationSpeedButton.setOnAction(e -> {
           respondToButtonPress(“respondToDecAnimationSpeed”);
        });
       
        // WHEN THE WINDOWCLOSES, KILL THE ANIMATION THREAD
       primaryStage.setOnCloseRequest(e->{
           if (animationThread != null) {
               animationThread.closeApp();
           }
        });

        // OPEN THEWINDOW
       primaryStage.show();
    }

    /**
     * Helper method for making a simpletextual button.
     */
    private Button makeButton(String text) {
       javafx.scene.control.Button b = newjavafx.scene.control.Button(text);
       b.setStyle(“-fx-font-size:14pt; -fx-padding:10px;”);
        return b;
    }

    /**
     * This method employs reflection toprocess button clicks
     * such that it can lock access to theanimation variables
     * first and then unlock accessafter.
     */
    private void respondToButtonPress(StringhandlerMethodName) {
        try {
           // MAKE SURE NO OTHER CODE TRIES TO CHANGE THINGS
           // BEFORE WE’RE DONE WITH HANDLING THIS RESPONSE
           animationLock.lock();
           
           // PAUSE THE ANIMATION WHILE WE’RE FIGURING OUT
           // WHAT THE RESPONSE SHOULD BE
           restartAnimation =animationThread.getKeepAnimatingProperty().getValue();
           animationThread.setKeepAnimating(false);
           
           // HERE IS WHERE REFLECTION CALLS THE NAMED EVENT HANDLINGMETHOD
           Class colorListAppClass = this.getClass();
           Method handlerMethod =colorListAppClass.getMethod(handlerMethodName);
           handlerMethod.invoke(this);
           
           // RESTART THE ANIMATION IF NECESSARY
           if (restartAnimation) {
               // NOTE THAT THIS WILL FORCE A REPAINT
               respondToStartAnimation();
           }
           else {
               // REPAINT WITH WHATEVER THE UPDATE MAY BE. NOTE THAT
               // Platform.runLaber IS JavaFX’s WAY OF MAKING SURE
               // MULTIPLE THREADS AREN’T TRYING TO DO THINGSSIMULTANEOUSLY,
               // LIKE DRAW TO THE CANVAS.
               Platform.runLater(()->{
                   colorCanvas.repaint();
               });
           }
        } catch(NoSuchMethodException | IllegalAccessException |InvocationTargetException exc) {
           // ALWAYS UNLOCK TO AVOID DEADLOCK
           animationLock.unlock();
           exc.printStackTrace();
        } finally {
           // ALWAYS UNLOCK TO AVOID DEADLOCK
           animationLock.unlock();
        }
    }

    /**
     * Helper method for displaying a simplemessage dialog.
     */
    private void showMessageDialog(Alert.AlertTypealertType, String title, String message) {
        Alert dialog = newAlert(alertType);
       dialog.setTitle(title);
       dialog.setHeaderText(null);
       dialog.setContentText(message);
       dialog.showAndWait();
    }

    // HANDLES PRESSING THE ADD COLOR, IT ADDSONE COLOR TO THE LIST
    public void respondToAddColor() {
        if (colorList.size()< colorCanvas.MAX_NODES) {
           Color randomColor = Color.color((float) Math.random(), (float)Math.random(), (float) Math.random());
           colorList.addLast(randomColor);
        } else {
           showMessageDialog(AlertType.WARNING, “No More Colors”, “That’senough Colors for now”);
        }
    }

    // HANDLES PRESSING ADD ALL REDS, IT ADDS 512REDS TO THE LIST
    public void respondToAddAllReds() {
        colorList.clear();
        for (int i = 0; i <256; i += 1) {
           double r = i / 255.0;
           Color newRed = Color.color(r, 0, 0);
           colorList.addLast(newRed);
        }
        for (int i = 255; i >-1; i -= 1) {
           double r = i / 255.0;
           Color newRed = Color.color(r, 0, 0);
           colorList.addLast(newRed);
        }
    }

    // HANDLES ADDING YELLOW, MAGENTA, ANDCYAN
    public void respondToAddYellowToMagentaToCyan(){
        colorList.clear();
        int r = 255, g = 255, b= 0;
        // YELLOW TOMAGENTA
        for (int i = 0; i <256; i++) {
           Color colorToAdd = Color.color(r/255.0, g/255.0, b/255.0);
           colorList.addLast(colorToAdd);
           if (i < 255) {
               g–;
               b++;
           }
        }
        // MAGENTA TO CYAN
        for (int i = 0; i <256; i++) {
           Color colorToAdd = Color.color(r/255.0, g/255.0, b/255.0);
           colorList.addLast(colorToAdd);
           if (i < 255) {
               r–;
               g++;
           }
        }
        // CYAN BACK TOYELLOW
        for (int i = 0; i <256; i++) {
           Color colorToAdd = Color.color(r/255.0, g/255.0, b/255.0);
           colorList.addLast(colorToAdd);
           if (i < 255) {
               r++;
               b–;
           }
        }
    }

    // HANLES ADDING RED, GREEN, AND, BLUE TOLIST
    public void respondToAddRGB() {
        colorList.clear();
        for (int i = 0; i <256; i += 1) {
           Color redToAdd = Color.color(i / 255.0, 0, 0);
           colorList.addLast(redToAdd);
        }
        for (int i = 0; i <256; i += 1) {
           Color greenToAdd = Color.color(0, i / 255.0, 0);
           colorList.addLast(greenToAdd);
        }
        for (int i = 0; i <256; i += 1) {
           Color blueToAdd = Color.color(0, 0, i / 255.0);
           colorList.addLast(blueToAdd);
        }
    }

    // HANDLES MOVING THE FRONT ELEMENT TO THEEND
    public void respondToMoveFrontToLast() {
       colorList.moveFrontToLast();
    }

    // HANDLES MOVING THE LAST ELEMENT TO THEFRONT
    public void respondToMoveLastToFront() {
       colorList.moveLastToFront();
    }

    // HANDLES REVERSING THE LIST
    public void respondToReverseList() {
       colorList.reverse();
    }

    // HANDLES REMOVING ALL COLORS FROM THELIST
    public void respondToRemoveColors() {
        colorList.clear();
    }

    // HANDLES STARTING THE ANIMATOR
    public void respondToStartAnimation() {
       animationThread.setKeepAnimating(true);
    }

    // HANDLES STOPPING THE ANIMATOR
    public void respondToStopAnimation() {
       animationThread.setKeepAnimating(false);
        restartAnimation =false;
    }

    // HANDLES INCREMENTING THE ANIMATIONSPEED
    public void respondToIncAnimationSpeed() {
        incFps(5);
    }

    // HANDLES DECREMENTING THE ANIMATIONSPEED
    public void respondToDecAnimationSpeed() {
        incFps(-5);
    }

    /**
     * Accessor method for getting theanimation speed. It is
     * synchronized because there may bemultiple threads in this
     * application that need to use thisinformation simultaneously.
     */
    public IntegerProperty getFpsProperty() {
        return fps;
    }

    /**
     * Mutator method for setting the animationspeed. It is
     * synchronized because there may bemultiple threads in this
     * application that need to use thisinformation simultaneously.
     */
    public void incFps(int deltaFps) {
        // ADD THE DELTAVALUE
       fps.setValue(fps.getValue() + deltaFps);
       
        // AND CLAMP THE FRAMESPER SECOND.
        if (fps.getValue() <MIN_FPS) {
           fps.setValue(MIN_FPS);
        } else if(fps.getValue() > MAX_FPS) {
           fps.setValue(MAX_FPS);
        }
    }

    /**
     * The AnimationTimer class provides ouranimation timing for us.
     */
    class AnimationTimer extends Thread {
        // TURNING THIS TO trueWILL KILL THE ANIMATOR
        boolean appClosed =false;
       
        // TURNING THIS TO FALSEWILL PAUSE ANIMATION
        BooleanPropertykeepAnimating = new SimpleBooleanProperty(true);

        // FOR KILLING THEANIMATOR
        public void closeApp(){
           appClosed = true;
        }
       
        // ACCESSOR FOR GETTINGIF THE ANIMATOR IS PAUSED OR NOT
        public BooleanPropertygetKeepAnimatingProperty() {
           return keepAnimating;
        }

        // FORPAUSING/UNPAUSING THE ANIMATOR
        public voidsetKeepAnimating(boolean initKeepAnimating) {
           keepAnimating.setValue(initKeepAnimating);
        }

        /**
         * When thisanimationThread is started, the run method is called.
         * It performstimed rendering of the list.
         */
        public void run(){
           // WHEN THE APP CLOSES EXIT THIS METHOD
           while (!appClosed) {
               // IF WE’RE NOT PAUSED
               if (keepAnimating.getValue()) {
                   try {
                       // LOCK ACCESS TO AVOID RACE CONDITIONS
                       animationLock.lock();

                       // WHICH LIST METHOD SHOULD BE USED EACH
                       // FRAME OF ANIMATION?
                       if (reverseCheckBox.isSelected()) {
                           // REVERSE
                           colorList.moveFrontToLast();
                       } else {
                           // FORWARD
                           colorList.moveLastToFront();
                       }
                       
                       // RENDER THE LIST
                       Platform.runLater(()->{
                           colorCanvas.repaint();
                       });                       
                   } finally {
                       // RELASE THE LOCK
                       animationLock.unlock();
                   }
               }
               try {
                   // REST BRIEFLY TO ENSURE PROPER TIMING
                   // AND TO ALLOW THE GUI TO GET SOME OPERATIONS
                   // EXECUTED
                   if (keepAnimating.getValue()) {
                       // ENSURES A CONSISTENT FRAME RATE
                       Thread.sleep(1000 / fps.getValue());
                   } else {
                       // DON’T BE A RESOURCE HOG
                       Thread.sleep(100);
                   }
               } catch (InterruptedException ie) {
                   ie.printStackTrace();
               }
           }
        }
    }

    /**
     * This method launches the ColorListAppJavaFX app, which
     * constructs it and then forces a call tostart.
     */
    public static void main(String[] args) {
        launch();
    }
}

package part_two_color_animation;

import java.util.Iterator;

/**
* GenericDoublyLinkedList.java
*
* YOU MUST FILL IN THE CODE FOR THE FOLLOWING FOUR METHODS:
* -clear
* -moveFrontToLast
* -moveLastToFront
* -reverse
*
*/
public class GenericDoublyLinkedList<E> {

    // YOU’LL NEED TO CAREFULLY MAINTAIN THE head& tail
    private GenericNode head = null;
    private GenericNode tail = null;
    private int size = 0;

    // DEFAULT CONSTRUCTOR
    public GenericDoublyLinkedList() {
       
    }

    /**
     * This method simply adds a new node tothe end of the list.
     * Do not need to change this method, itworks properly.
     */
    public void addLast(E dataToAdd) {
        size++;
        GenericNode newNode =new GenericNode(dataToAdd, tail, null);
        if (head == null){
           head = newNode;
           tail = head;
        } else {
           tail.next = newNode;
           tail = newNode;
        }
    }

    /**
     * You need to define this one. It simplyempties the list
     * of all data (all nodes).
     */
    public void clear() {
        // ADD YOUR CODEHERE
    }

    /**
     * You need to define this one. It shouldtake the first node
     * in the list and move it to theend.
     */
    public void moveFrontToLast() {
        // ADD YOUR CODEHERE
    }

    /**
     * You need to define this one. It shouldtake the last node
     * in the list and move it to thefront.
     */
    public void moveLastToFront() {
        // ADD YOUR CODEHERE
    }

    /**
     * You need to define this one. It reversesthe order of the
     * nodes in the list.
     */
    public void reverse() {
        // ADD YOUR CODEHERE
    }

    /**
     * Accessor method for getting the size ofthe list. You do
     * not have to change this method.
     */
    public int size() {
        return size;
    }

    /**
     * This method provides an Iterator foriterating through the
     * list. You should not change this methodor the custom
     * Iterator class,SortedGenericListIterator.
     */
    public Iterator listIterator() {
        return newSortedGenericListIterator();
    }

    /**
     * This is just a basic Iterator, don’tchange it.
     */
    class SortedGenericListIterator implementsIterator {
        // THE ITERATOR’STRAVELLER STARTS AT THE HEAD
        private GenericNodetraveller = head;

        publicSortedGenericListIterator() {
           
        }

        // HAVE WE REACHEDTHE END OF THE LIST?
        public boolean hasNext(){
           if (traveller == null) {
               return false;
           } else {
               return true;
           }
        }

        // GET THE NEXTELEMENT IN THE LIST
        public Object next(){
           if (traveller == null) {
               return null;
           }

           Object dataToReturn = traveller.data;
           traveller = traveller.next;
           return dataToReturn;
        }

        // WE WON’T USE THISMETHOD
        public void remove(){}
    }

    /**
     * Node for a generic doubly linked list.It can store any
     * type of object.
     */
    class GenericNode<E> {
        // DOUBLY LINKED LISTNODE
        E data;
        protected GenericNodeprev;
        protected GenericNodenext;

        public GenericNode(EdataToAdd, GenericNode initPrev, GenericNode initNext) {
           data = dataToAdd;
           prev = initPrev;
           next = initNext;
        }
    }
}

Thank you for reading, and help

Have a nice day.

Expert Answer


Answer to Part Used Singly Linked List Node Knows Next Node List Previous Doubly Linked List Nodes K Q27825212 . . .

OR