From 4968dfb1f0de354b6d2fdf5b2e688874c3df4604 Mon Sep 17 00:00:00 2001 From: Antesh Sharma Date: Wed, 16 Feb 2022 22:20:28 +0530 Subject: [PATCH] Added solution to find loop in linkedlist --- .../com/antesh/dsa/ArrayToLinkedList.java | 2 - .../nvidia/FindLoopInLinkedList.java | 65 +++++++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/antesh/interview/nvidia/FindLoopInLinkedList.java diff --git a/src/main/java/com/antesh/dsa/ArrayToLinkedList.java b/src/main/java/com/antesh/dsa/ArrayToLinkedList.java index 691a7e4..3fce1b4 100644 --- a/src/main/java/com/antesh/dsa/ArrayToLinkedList.java +++ b/src/main/java/com/antesh/dsa/ArrayToLinkedList.java @@ -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; diff --git a/src/main/java/com/antesh/interview/nvidia/FindLoopInLinkedList.java b/src/main/java/com/antesh/interview/nvidia/FindLoopInLinkedList.java new file mode 100644 index 0000000..5367d39 --- /dev/null +++ b/src/main/java/com/antesh/interview/nvidia/FindLoopInLinkedList.java @@ -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; + } +}