Monday, March 31, 2014

Linked List Cycle

Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space? 
Solution 1: reverse the list, if there is a circle, it will point back to head.
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) return false;
        
        ListNode curA = head;
        ListNode curB = curA.next;
        while (curB.next != null) {
            if (curB == head) return true; //cycle found
            if (curB.next != null) {
                ListNode curC = curB.next;
                curB.next = curA; // reverse A->B to B->A
                curA = curB;
                curB = curC;
            }
        }
        return false;
    }
}
Solution 2: traverse the list, if a node does not point to itself, then make it point to itself and process next node. If a node points to itself, then there must be a cycle.
public class Solution {
    public boolean hasCycle(ListNode head) {
        while(head != null && head.next != null) {
            ListNode tmp = head.next;
            head.next = head; //make the node point to itself
            head = tmp;
            if (head.next == head) return true;
        }
        return false;
    }   
}
Solution 3: fast runner and slow runner, won't change the list.
public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) return true;
        }
        return false;   
    }   
}

No comments:

Post a Comment