Skip to content

Added solution to find loop in linkedlist #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions src/main/java/com/antesh/dsa/ArrayToLinkedList.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ public static Node insertUsingWhileLoop(Node root, int data) {
if (root == null) {
root = temp;
} else {


Node ptr = root;
while (ptr.next != null) {
ptr = ptr.next;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.antesh.interview.nvidia;

/*
* Goal is to find the loop in LinkedList without extra space
* */

public class FindLoopInLinkedList {

public static Node root;

public static Node insertNode(Node root, int data) {
Node temp = new Node();
temp.data = data;
temp.next = null;

if (root == null) {
root = temp;
} else {
Node ptr = root;
while (ptr.next != null) {
ptr = ptr.next;
}
ptr.next = temp;
}
return root;
}

public static boolean detectLoop() {
Node p_slow = root;
Node p_fast = root;

while (p_slow != null && p_fast != null && p_fast.next != null) {
p_slow = p_slow.next;
p_fast = p_fast.next.next;
if (p_fast == p_slow) {
return true;
}
}
return false;
}

public static void print(Node root) {
while (root != null) {
System.out.print(root.data + " -> ");
root = root.next;
}
System.out.println();
}

//driver
public static void main(String[] args) {
int[] arr = new int[]{5, 25, 10, 35, 40};
for (int num : arr) {
root = insertNode(root, num);
}

print(root);
System.out.println("Is Loop present in LinkedList? \nAns: " + detectLoop());
}

static class Node {
int data;
Node next;
}
}