Pages

Wednesday, September 3, 2025

Remove Cycle in LL using Java

 class Node {

    int data;
    Node next;

    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

class LinkedList {
    Node head;

    public void add(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
            return;
        }
        Node temp = head;
        while (temp.next != null) {
            temp = temp.next;
        }
        temp.next = newNode;
    }

    public void printList() {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
        System.out.println();
    }

    // ✅ cycle detection
    public boolean isCycle() {
        Node slow = head;
        Node fast = head;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return true; // cycle exists
            }
        }
        return false;
    }

    // ✅ cycle removal
    public void removeCycle() {
        Node slow = head;
        Node fast = head;
        boolean cycle = false;

        // Step 1: Detect cycle
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (fast == slow) {
                cycle = true;
                break;
            }
        }
        if (!cycle) return; // no cycle found

        // Step 2: Move slow back to head
        slow = head;
        Node prev = null;

        // Step 3: Find meeting point
        while (slow != fast) {
            prev = fast;     // track last node
            slow = slow.next;
            fast = fast.next;
        }

        // Step 4: Break the cycle
        prev.next = null;
    }
}

public class Main {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();

        // creating a cycle manually: 1 -> 2 -> 3 -> back to 2
        list.head = new Node(1);
        list.head.next = new Node(2);
        list.head.next.next = new Node(3);
        list.head.next.next.next = list.head.next; // cycle

        System.out.println("Has cycle? " + list.isCycle()); // true ✅
        list.removeCycle();
        System.out.println("Has cycle? " + list.isCycle()); // false ✅

        // Now safe to print
        list.printList(); // 1 2 3
    }
}

No comments:

Post a Comment

remove duplicates from sorted array - two pointer approach (leetcode)

  class Solution {     public int removeDuplicates ( int [] nums ) {         // base case: return if array have no el.         if ( nums...