how can i take the input as that of linked list ?
How to construct input LL
import java.util.Scanner;
public class Main {
private class Node {
int data;
Node next; // holds value of next address where to point
}
private static Node head; // to store initial address
private static Node tail;// to store final address
private static int size;
public int size() {
return this.size;
}
public int addLast(int item) {
int i = 0;
int flag = 0;
if (this.size() > 0) {
Node temp = head;
while (temp != null) {
if (item == temp.data) {
flag = 1;
break;
}
i++;
temp = temp.next;
}
}
if (flag == 1) {
Node temp = this.head;
for (int j = 0; j < i; j++) {
temp = temp.next;
}
this.tail.next = temp;
return 1;
}
// create a new node
Node nn = new Node();
nn.data = item;
nn.next = null;
// attach
if (size >= 1) {
this.tail.next = nn;
}
// summary object
if (size == 0) {
this.head = nn;
this.tail = nn;
this.size++;
} else {
this.tail = nn;
this.size++;
}
return 0;
}
public void detectLoop(Node node) {
Node slow = this.head;
Node fast = this.head;
while (slow != null && fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
removeLoop(slow, node);
}
}
}
public void removeLoop(Node slow, Node node) {
Node start = head;
Node loop = slow;
if (start == loop) {
loop = loop.next;
while (start != loop.next) {
loop = loop.next;
}
} else {
while (start.next != loop.next) {
start = start.next;
loop = loop.next;
}
}
loop.next = null;
}
void printList() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Main list = new Main();
while (true) {
int n = sc.nextInt();
if (n != -1) {
int a = list.addLast(n);
if (a == 1)
break;
} else {
break;
}
}
list.detectLoop(head);
list.printList();
}
}
@rishabhkk Bro this is the complete code for this problem. Take reference from this code and then solve it again by yourself.