LeetCode 141 - 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:

public boolean hasCycle(ListNode head) {
    ListNode walker = head, runner = head;
    do {
        if(runner == null || runner.next == null) 
            return false;
        walker = walker.next;
        runner = runner.next.next;
    } while(walker != runner);
    return true;
}

 

Solution 2:

public boolean hasCycle(ListNode head) {
    if(head == null) return false;
    ListNode walker = head, runner = head.next;
    while(runner != null) {
        if(walker == runner) return true;
        walker = walker.next;
        runner = runner.next;
        if(runner != null) 
            runner = runner.next;
    } 
    return false;
}

 

你可能感兴趣的:(LeetCode)