Answered step by step
Verified Expert Solution
Question
1 Approved Answer
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.
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: LLL = 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{ private static class Node { private E element; private Node next; public Node(E e, Node n){ element = e; next = n; } public E getE(){ return element; } public Node getNext(){ return next; } public void setE(E e){ element = e; } public void setNext(Node n){ next = n; } } private Node head; public Linkedlist(){ head = null; } public void add(E e){ Node temp = new Node<>(e, head); head = temp; } public void insert(E e, Node p, Node n){ p.setNext(new Node<>(e, n)); } public Node getNode(int i) throws Exception{ Node temp = head; while (i > 0){ if (temp == null) throw new Exception("OoB"); temp = temp.getNext(); i--; } return temp; } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started