How should i proceed with this problem
Dont know from where to start
How can we do this without any custom format given
I mean linkedlist is not given
Please reply!?// (appraiching limit)
hey @bhavik911
just Create LinkedList which contains loop.
and detect the loop.
What you need to do is that you have to first create a loop from the array that is given in input. For example :
if array is given as 1 2 3 4 5 2 3 -1 then when you see that after 5 you encounter 2 which is already present then you have to make 5->next = 2; this is how you have to make loop. Then you have to detect this loop and remove it.
So at each point I need to check ?
Whether already present or not?
When you create a linked list
Dont understand this quite
when you add data in LinkedList tb check kroge 2 is present or not
So I have to write a function that goes through entire list each time I add a value?
I know the logic and code, but dont know how to do it by taking input from own and building my own cicular linked list , how will I connect it
Please share the code regarding it , I dont get it
import java.util.Scanner;
public class circularLL {
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);
circularLL list = new circularLL();
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();
}
}