Question

iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains...

iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains a loop. Print true if yes, false if not.
Test by using the following code:

                LL<Integer> L = new LL<>();
        for (int i = 1000; i > 0; i-=3) sl.add(i);   
                try {
                        L.insert(122, L.getNode(70), L.getNode(21));
                        if (L.detectLoop()) System.out.println("True");
                        else System.out.println("False.");
            }
       catch(Exception e){
                        e.printStackTrace();
                }
class Linkedlist<E>{
        private static class Node<E>{
                private E element;
                private Node<E> next;
                public Node(E e, Node<E> n){
                        element = e;
                        next = n;
                }
                public E getE(){
                        return element;
                }
                public Node<E> getNext(){
                        return next;
                }
                public void setE(E e){
                        element = e;
                }
                public void setNext(Node<E> n){
                        next = n;
                }
        }
        private Node<E> head;
        public Linkedlist(){
                head = null;
        }
        public void add(E e){
                Node<E> temp = new Node<>(e, head);                 
                head = temp;
        }
        public void insert(E e, Node<E> p, Node<E> n){
                p.setNext(new Node<>(e, n));      
        }
        public Node<E> getNode(int i) throws Exception{
                Node<E> temp = head;
                while (i > 0){
                        if (temp == null) throw new Exception("OoB");
                        temp = temp.getNext();
                        i--;
                }
                return temp;
        }
        
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

As you asked me to write the detectloop function using your code provided by you I created a new function detectloop in class Linkedlist. I used Floyd's cycle finding algo to find a loop in the linked list. After that, I created a LinkedList_test class to test the detectloop function. Every change I have done in the code are in BOLD.

Code:-

class Linkedlist<E>

{

    private static class Node<E>

    {

        private E element;

        private Node<E> next;

       

        public Node(E e, Node<E> n)

        {

            element = e;

            next = n;

        }

       

        public E getE()

        {

            return element;

        }

       

        public Node<E> getNext()

        {

            return next;

        }

       

        public void setE(E e)

        {

            element = e;

        }

                

        public void setNext(Node<E> n)

        {

            next = n;

        }

    }

   

    private Node<E> head;

   

    public Linkedlist()

    {

        head = null;

    }

   

    public void add(E e)

    {

        Node<E> temp = new Node<>(e, head);                

        head = temp;

    }

    public void insert(E e, Node<E> p, Node<E> n)

    {

        p.setNext(new Node<>(e, n));     

    }

       

    public Node<E> getNode(int i) throws Exception

   {

        Node<E> temp = head;

        while (i > 0)

        {

            if (temp == null) throw new Exception("OoB");

            temp = temp.getNext();

            i--;

        }

        return temp;

    }

   

    //i am creating detect loop function using Floydd's Cycle finding algoritham

    public boolean detectLoop()

    {

        //created two pointers slow and fast

        //slow pointer move by one Node

        //fast pointer move by two Node

        Node<E> fast=head;

        Node<E> slow=head;

       

        //loop is going to run until every condiotn in loop is true

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

        {

            //fast move by two node

            fast=fast.next.next;

            //slow move by one node

            slow=slow.next;

           

            //if they point to same node anytime that means there is a loop in the linked list

            if(fast==slow)

            {

                return true;

            }

           

        }

        return false;

    }

       

}

public class Linkedlist_test

{

    public static void main (String[] args)

    {

        Linkedlist<Integer> L = new Linkedlist<>();

        for (int i = 1000; i > 0; i-=3)

        L.add(i);  

        try

        {

            L.insert(122, L.getNode(70), L.getNode(21));

            if (L.detectLoop()) System.out.println("True");

            else System.out.println("False.");

        }

        catch(Exception e)

        {

            e.printStackTrace();

        }

    }

}

output:-

Add a comment
Know the answer?
Add Answer to:
iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please answer in Java. The code that needs to be modified is below. Thank you. Question:...

    Please answer in Java. The code that needs to be modified is below. Thank you. Question: Implement Doubly Linked List add method which add an element to a specific position. - It’s an instance method that takes a position and an element, then adds the element to this specific position and shifts the element currently at this position and any subsequent elements to the right. It throws an exception if the position is out of bound. It traverses the list...

  • I am trying to make a linked list queue and I am trying to use the...

    I am trying to make a linked list queue and I am trying to use the display method I made just to see if its working but when I run it nothing is displayed please help. Also the newPlane boolean was made just so I can randomly decide if the plane is going to join the queue or not. public class PlaneSimulation { public static void main(String[] args) { int landTime = 2; int takeoffTime = 3; int avgArrivalInterval =...

  • Given a singly-linked list interface and linked list node class, implement the singly-linked list which has...

    Given a singly-linked list interface and linked list node class, implement the singly-linked list which has the following methods in Java: 1. Implement 3 add() methods. One will add to the front (must be O(1)), one will add to the back (must be O(1)), and one will add anywhere in the list according to given index (must be O(1) for index 0 and O(n) for all other indices). They are: void addAtIndex(int index, T data), void addToFront(T data), void addToBack(T...

  • Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time...

    Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time complexity is omitted. Any methods/functions below could be changed into something different. I was thinking of changing the method of getting size of list and maybe change from numbers to letters for nodes. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null;...

  • Doubly Linked List Is there a way to further modify/simplify/improve this program? I was thinking of maybe changing how...

    Doubly Linked List Is there a way to further modify/simplify/improve this program? I was thinking of maybe changing how to get size. I'm not sure. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null; prev = null; data = 0; } /* Constructor */ public Node(int d, Node n, Node p) { data = d; next = n; prev = p; } /* Function...

  • I need help with todo line please public class LinkedList { private Node head; public LinkedList()...

    I need help with todo line please public class LinkedList { private Node head; public LinkedList() { head = null; } public boolean isEmpty() { return head == null; } public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.getNext(); } return count; } public void add(int data) { Node newNode = new Node(data); newNode.setNext(head); head = newNode; } public void append(int data) { Node newNode = new Node(data);...

  • n JAVA, students will create a linked list structure that will be used to support a...

    n JAVA, students will create a linked list structure that will be used to support a role playing game. The linked list will represent the main character inventory. The setting is a main character archeologist that is traveling around the jungle in search of an ancient tomb. The user can add items in inventory by priority as they travel around (pickup, buy, find), drop items when their bag is full, and use items (eat, spend, use), view their inventory as...

  • Data Structures - Singly Linked Lists You will add a method swapNodes to SinglyLinkedList class (below). This method should swap two nodes node1 and node2 (and not just their contents) given reference...

    Data Structures - Singly Linked Lists You will add a method swapNodes to SinglyLinkedList class (below). This method should swap two nodes node1 and node2 (and not just their contents) given references only to node1 and node2. The new method should check if node1 and node2 are the same node, etc. Write the main method to test the swapNodes method. You may need to traverse the list. package linkedlists; public class SinglyLinkedList<E> implements Cloneable {    // ---------------- nested Node class...

  • Q) Modify the class Linked List below to make it a Doubly Linked List. Name your...

    Q) Modify the class Linked List below to make it a Doubly Linked List. Name your class DoublyLinkedList. Add a method addEnd to add an integer at the end of the list and a method displayInReverse to print the list backwards. void addEnd(int x): create this method to add x to the end of the list. void displayInReverse(): create this method to display the list elements from the last item to the first one. Create a main() function to test...

  • Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)...

    Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)    {        this.size = size;    }    /** Reference to list head. */    private Node<E> head = null;    /** The number of items in the list */    private int size = 0;       /** Add an item to the front of the list.    @param item The item to be added    */    public void addFirst(E...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT