package com.thealgorithms.datastructures.lists;
import java.util.Scanner;
public final class CreateAndDetectLoop {
private CreateAndDetectLoop() {
}
static void printList(Node head) {
Node cur = head;
while (cur != null) {
System.out.print(cur.value + " ");
cur = cur.next;
}
}
static void createLoop(Node head, int k) {
if (head == null) {
return;
}
Node temp = head;
int count = 1;
while (count < k) {
temp = temp.next;
count++;
}
Node connectedPoint = temp;
while (temp.next != null) {
temp = temp.next;
}
temp.next = connectedPoint;
}
static boolean detectLoop(Node head) {
Node sptr = head;
Node fptr = head;
while (fptr != null && fptr.next != null) {
sptr = sptr.next;
fptr = fptr.next.next;
if (fptr == sptr) {
return true;
}
}
return false;
}
public static void main(String[] args) {
SinglyLinkedList singlyLinkedList = new SinglyLinkedList();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements to be inserted: ");
int n = sc.nextInt();
System.out.printf("Enter the %d elements: %n", n);
while (n-- > 0) {
singlyLinkedList.insert(sc.nextInt());
}
System.out.print("Given list: ");
printList(singlyLinkedList.getHead());
System.out.println();
System.out.println("Enter the location to generate loop: ");
int k = sc.nextInt();
createLoop(singlyLinkedList.getHead(), k);
if (detectLoop(singlyLinkedList.getHead())) {
System.out.println("Loop found");
} else {
System.out.println("No loop found");
}
sc.close();
}
}