Question

In: Computer Science

package labs; Complete the following code /* * Purpose: Look at LinkedList, overloaded methods and *...

package labs;

Complete the following code
/*
 * Purpose: Look at LinkedList, overloaded methods and
 * write a simple method to check if the LinkedList actually contains any loops/cycles in it.
 */
public class LinkedList<E> {
        private static class Node<E>
        {
                E data;
                Node<E> next;

                public Node(E d)
                {
                        data=d;
                        next=null;
                }
        }
        private Node<E> head;
        private Node<E> tail;

        /*
         * data of type E, first gets put into a Node
         * and then the Node gets added onto the Linked List
         * Note: This method has been overloaded.
         */
        public void add(E data)
        {
                Node<E> temp=new Node<>(data);
                /*
                 * the linked list is empty!
                 */
                if (head==null)
                {
                        head=temp;
                        tail=temp;
                }
                else
                {
                        tail.next=temp;
                        tail=temp;
                }
        }


        /*TODO
         * The nodeData is already of type Node<E> and hence
         * gets put onto the LinkedList immediately.
         * Note: This method has been overloaded.
         */
        public void add(Node<E> nodeData)
        {

        }


        /*
         * This method checks if there is any loops in the linked list.
         * If there is a loop, then the method must return back the start of
         * the loop. If there is no loop, then the method must return back null.
         */
        public Node<E> getStartOfLoopNode()
        {
                Node<E> fast=head;
                Node<E> slow=head;
                boolean isLoopy=false;



                while (fast!=null && fast.next!=null)
                {
                        /*TODO
                         * the fast pointer moves at twice the speed of slow pointer.
                         * if slow and fast meet there exists a loop
                         */


                }


                                /*TODO
                                 * if there is a loop return the head else return slow
                                 * reset the slow pointer back to head.
                                 * Now make the slow pointer and fast pointer move at the same speed.
                                 * Where they meet, is the point of intersection.
                                 */

                return null;

        }


        public static void main(String []args)
        {
                LinkedList<String> ll1 = createLinkedListWithNoLoops();
                LinkedList<String> ll2 = createLinkedListWithLoops();

                /*
                 * when you call ll2.getStartOfLoopNode it must return back the node with CS350
                 * when you call ll1.getStartOfLoopNode it must return back the node null
                 */
                Node<String> startOfLoop=ll2.getStartOfLoopNode();
                if (startOfLoop==null)
                        System.out.println("There is no loop");
                else
                        System.out.println("The loop begins from "+startOfLoop.data.toString());
        }

        private static LinkedList<String> createLinkedListWithLoops() {
                /*
                 * adding some courses at BU. This now has a loop in it!
                 */

                LinkedList<String> ll2=new LinkedList<String>(); //this is linkedList 2
                /*
                 * adding some courses at BU. Note this linked list does contain loop!
                 */
                ll2.add("CS112");
                ll2.add("CS131");
                ll2.add("CS132");
                ll2.add("CS235");
                Node<String> loop=new Node<String>("CS350");
                ll2.add(loop);
                ll2.add("CS411");
                ll2.add("CS421");
                ll2.add("CS112");
                ll2.add("CS131");
                ll2.add(loop);
                return ll2;
        }

        private static LinkedList<String> createLinkedListWithNoLoops() {
                LinkedList<String> ll1=new LinkedList<String>(); //this is linkedList 1
                /*
                 * adding some courses at BU. Note this linked list does not contain any loops!
                 */
                ll1.add("CS112");
                ll1.add("CS131");
                ll1.add("CS132");
                ll1.add("CS350");
                ll1.add("CS112");
                return ll1;
        }
}

Solutions

Expert Solution

public class LinkedList<E> {

private static class Node<E>

{

E data;

Node<E> next;

public Node(E d)

{

data=d;

next=null;

}

}

private Node<E> head;

private Node<E> tail;

/*

* data of type E, first gets put into a Node

* and then the Node gets added onto the Linked List

* Note: This method has been overloaded.

*/

public void add(E data)

{

Node<E> temp=new Node<>(data);

/*

* the linked list is empty!

*/

if (head==null)

{

head=temp;

tail=temp;

}

else

{

tail.next=temp;

tail=temp;

}

}


/*TODO

* The nodeData is already of type Node<E> and hence

* gets put onto the LinkedList immediately.

* Note: This method has been overloaded.

*/

public void add(Node<E> nodeData)

{

/*

* the linked list is empty!

*/

if (head==null) //since only one node loop points to itself

{

head=nodeData;

tail=nodeData;

}

else

{

Node<E> temp=head;

while(temp!=null)// check the list to see is node to be inserted is already present in the list

{

if(temp==nodeData)// if present point the tail to already present node to create a loop and return

{

tail.next=temp;

tail=temp;

return;

}

temp=temp.next;

}

// if not present then simply add the new node to the tail

tail.next=nodeData;

tail=nodeData;

return;

}

}


/*

* This method checks if there is any loops in the linked list.

* If there is a loop, then the method must return back the start of

* the loop. If there is no loop, then the method must return back null.

*/

public Node<E> getStartOfLoopNode()

{

Node<E> fast=head;

Node<E> slow=head;

boolean isLoopy=false;

// move slow and fast pointer

slow=slow.next;

fast=fast.next.next;

while (fast!=null && fast.next!=null)

{

/*TODO

* the fast pointer moves at twice the speed of slow pointer.

* if slow and fast meet there exists a loop

*/

if(slow==fast) //see if they met or not

{

isLoopy=true; // set loop=true if met

break;

}

// else move slow one step and fast 2 steps

slow=slow.next;

fast=fast.next.next;

}

/*TODO

* if there is a loop return the head else return slow

* reset the slow pointer back to head.

* Now make the slow pointer and fast pointer move at the same speed.

* Where they meet, is the point of intersection.

*/

if(isLoopy==true)

{

// start one pointer from head and one from meeting point and where both meet that is point of intersection

// this shows that meeting point is the mid point of the linked list

slow=head;

while (slow != fast)

{

slow = slow.next;

fast = fast.next;

}

return(slow);

}

return null;

}


public static void main(String []args)

{

LinkedList<String> ll1 = createLinkedListWithNoLoops();

LinkedList<String> ll2 = createLinkedListWithLoops();

/*

* when you call ll2.getStartOfLoopNode it must return back the node with CS350

* when you call ll1.getStartOfLoopNode it must return back the node null

*/

Node<String> startOfLoop=ll2.getStartOfLoopNode();

if (startOfLoop==null)

System.out.println("There is no loop");

else

System.out.println("The loop begins from "+startOfLoop.data.toString());

}

private static LinkedList<String> createLinkedListWithLoops() {

/*

* adding some courses at BU. This now has a loop in it!

*/

LinkedList<String> ll2=new LinkedList<String>(); //this is linkedList 2

/*

* adding some courses at BU. Note this linked list does contain loop!

*/

ll2.add("CS112");

ll2.add("CS131");

ll2.add("CS132");

ll2.add("CS235");

Node<String> loop=new Node<String>("CS350");

ll2.add(loop);

ll2.add("CS411");

ll2.add("CS421");

ll2.add("CS112");

ll2.add("CS131");

ll2.add(loop);

return ll2;

}

private static LinkedList<String> createLinkedListWithNoLoops() {

LinkedList<String> ll1=new LinkedList<String>(); //this is linkedList 1

/*

* adding some courses at BU. Note this linked list does not contain any loops!

*/

ll1.add("CS112");

ll1.add("CS131");

ll1.add("CS132");

ll1.add("CS350");

ll1.add("CS112");

return ll1;

}

}


Related Solutions

Code in Java Given the LinkedList class that is shown below Add the following methods: add(String...
Code in Java Given the LinkedList class that is shown below Add the following methods: add(String new_word): Adds a linkedlist item at the end of the linkedlist print(): Prints all the words inside of the linkedlist length(): Returns an int with the length of items in the linkedlist remove(int index): removes item at specified index itemAt(int index): returns LinkedList item at the index in the linkedlist public class MyLinkedList { private String name; private MyLinkedList next; public MyLinkedList(String n) {...
Write a class that has three overloaded static methods for calculating the areas of the following...
Write a class that has three overloaded static methods for calculating the areas of the following geometric shapes: - circles - rectangles - cylinders Here are the formulas for calculating the area of the shapes. Area of a circle: Area = π r2, where p is Math.PI and r is the circle's radius Area of a rectangle: Area = Width x Length Area of a cylinder: Area = π r2 h, where p is Math.PI, r is the radius of...
Write a class that has three overloaded static methods for calculating the areas of the following...
Write a class that has three overloaded static methods for calculating the areas of the following geometric shapes: - circles - rectangles - cylinders Here are the formulas for calculating the area of the shapes. Area of a circle: Area = π r2, where p is Math.PI and r is the circle's radius Area of a rectangle: Area = Width x Length Area of a cylinder: Area = π r2 h, where p is Math.PI, r is the radius of...
//Complete the incomplete methods in the java code //You will need to create a driver to...
//Complete the incomplete methods in the java code //You will need to create a driver to test this. public class ManagedArray { private int[] managedIntegerArray; //this is the array that we are managing private int maximumSize; //this will hold the size of the array private int currentSize = 0; //this will keep track of what positions in the array have been used private final int DEFAULT_SIZE = 10; //the default size of the array public ManagedArray()//default constructor initializes array to...
Java: Complete the methods marked TODO. Will rate your answer! -------------------------------------------------------------------------------------------------- package search; import java.util.ArrayList; import...
Java: Complete the methods marked TODO. Will rate your answer! -------------------------------------------------------------------------------------------------- package search; import java.util.ArrayList; import java.util.List; /** * An abstraction over the idea of a search. * * @author liberato * * @param <T> : generic type. */ public abstract class Searcher<T> { protected final SearchProblem<T> searchProblem; protected final List<T> visited; protected List<T> solution; /**    * Instantiates a searcher.    *    * @param searchProblem    *            the search problem for which this searcher will find and   ...
As in previous labs, please write the Java code for each of the following exercises in...
As in previous labs, please write the Java code for each of the following exercises in BlueJ. For each exercise, write a comment before the code stating the exercise number. Make sure you are using the appropriate indentation and styling conventions Exercise 1 (15 Points) In BlueJ, create a new project called Lab6 In the project create a class called Company Add instance data (fields) for the company name (a String) and the sales for the current period (a double)...
Complete the methods in AQueue and ArrayQueue The third pasted code is just the interface. DO...
Complete the methods in AQueue and ArrayQueue The third pasted code is just the interface. DO NOT CHANGE ANY CODE ONLY ADD TO THE METHODS IN THE TWO CLASSES DESCRIBED import java.util.EmptyStackException; import java.util.NoSuchElementException; /** * AQueue provides default implementations for several no-brainer methods in the IQueue interface. * <p> * Some methods in IQueue are pairs that do the same job, but report failure differently. * Implement the fail-by-throwing methods here, in this abstract class, * by calling the...
Use Packet Tracer to complete the following labs. Answer the questions and record screenshots in a...
Use Packet Tracer to complete the following labs. Answer the questions and record screenshots in a Word document labeled firstInitial+LastName+Communications. In this lab, students will explore how ping, traceroute, and the default gateway setting affect device communication. Execute this lab according to the following guidelines: Configure all devices on the network with the following IP addresses: Device IP Address Wrk1 192.168.15.1 Wrk2 192.168.15.2 Sidon1 192.168.15.250 Eden Fa0/0 192.168.15.254 Eden Fa0/1 192.168.16.254 Sidon2 192.168.16.2 Wrk12 192.168.16.1 Open the command prompt for...
Complete the following program:LinkedQueue.zip package jsjf; /** * Represents a node in a linked list. */...
Complete the following program:LinkedQueue.zip package jsjf; /** * Represents a node in a linked list. */ public class LinearNode<T> {    private LinearNode<T> next;    private T element;    /**    * Creates an empty node.    */    public LinearNode()    {        next = null;        element = null;    }    /**    * Creates a node storing the specified element.    * @param elem element to be stored    */    public LinearNode(T elem)...
Please complete the following code in challenge.c. The code for main.c and challenge.h is below that....
Please complete the following code in challenge.c. The code for main.c and challenge.h is below that. (Don't edit main.c or challenge.h, only edit challenge.c) The instructions are in the comments. Hint: the_person is declared in main, so you need to define it in challenge.c using extern challenge.c #include "challenge.h" //return: struct //param: (struct person p1, struct person p2) //TODO: create a function that returns the person who has a higher GPA. // 1. if GPAs are equal, then return the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT