Created
October 15, 2019 11:58
-
-
Save Ajay-Raj-S/f34931c9604cd4673c81d3feaa5c3fda to your computer and use it in GitHub Desktop.
To check for any loop existence in the Linked List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package datastructures; | |
import java.util.ArrayList; | |
public class checkLoop { | |
Node head = null; | |
Node last = null; | |
int size = 0; | |
static class Node { | |
int data = 0; | |
Node next = null; | |
Node(int val) { | |
data = val; | |
next = null; | |
} | |
} | |
private void insert(int val) { | |
Node newNode = new Node(val); | |
if(head == null) { | |
head = newNode; | |
last = newNode; | |
} else { | |
last.next = newNode; | |
last = newNode; | |
} | |
size++; | |
} | |
private Boolean checkForLoop() { | |
Node trav = head; | |
ArrayList<Node> arr = new ArrayList<>(); | |
int flag = 0; | |
int counter = 0; | |
while(trav != null) { | |
arr.add(trav); | |
counter++; | |
int inCounter = 0; | |
for(Object i : arr) { | |
if(inCounter < counter-1) { | |
if(trav == (Node) i) { | |
flag = 1; | |
break; | |
} | |
} | |
inCounter++; | |
} | |
trav = trav.next; | |
if(flag == 1) | |
break; | |
} | |
arr.clear(); | |
return flag == 1; | |
} | |
private void display() { | |
Node trav = head; | |
if(checkForLoop()) { | |
System.out.println("List is Modified!!, Loop exists"); | |
return; | |
} | |
do { | |
System.out.println(trav.data+ " " + trav.next); | |
trav = trav.next; | |
} while(trav != null); | |
} | |
private void changeTheData() { | |
// changes the last Node next to somewhere inside the list to form a Loop | |
last.next = head.next.next.next.next; | |
} | |
public static void main(String[] args) { | |
checkLoop cL = new checkLoop(); | |
cL.insert(1); | |
cL.insert(2); | |
cL.insert(3); | |
cL.insert(4); | |
cL.insert(5); | |
cL.insert(6); | |
cL.insert(7); | |
cL.display(); | |
cL.changeTheData(); | |
cL.display(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment