Check Linked List has Cycle

package org.wesome.dsalgo;

import lombok.Data;

import java.util.Objects;

public class LinkedList {
    static Node head;
    static int size = 0;

    public static boolean hasCycle() {
        System.out.println("LinkedList.hasCycle");
        if (Objects.isNull(head)) {
            System.out.println("list is null");
            return false;
        }
        Node slow = head;
        Node fast = head.next;
        while (Objects.nonNull(fast) && Objects.nonNull(fast.next)) {
            if (fast == slow) {
                System.out.println("slow is equals to fast, list has cycle \n");
                return true;
            } else {
                fast = fast.next.next;
                slow = slow.next;
            }
        }
        System.out.println("list does not has cycle \n");
        return false;
    }

    //this method print the list using loop
    static void printIteratively() {
        System.out.println("\nLinkedList.printIteratively");
        if (Objects.isNull(head)) {
            System.out.println("Linked List is null = " + head);
            return;
        }
        Node tempNode = head;
        System.out.println("Linked List Size is " + size);
        while (Objects.nonNull(tempNode)) {
            System.out.println("Node = " + tempNode.data);
            tempNode = tempNode.next;
        }
    }
}

@Data
class Node {
    int data;
    Node next;

    public Node(int data) {
        this.data = data;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static org.wesome.dsalgo.LinkedList.hasCycle;
import static org.wesome.dsalgo.LinkedList.head;

public class LinkedListTest {
    @Test
    void hasCycleTest() {
        addInLast();
        Assertions.assertTrue(hasCycle());
    }

    void addInLast() {
        head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);
        head.next.next.next.next.next = head.next;
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on