`

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;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics