Monday, July 28, 2014

[LeetCode] 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?

解题思路:
给两个指针,一个每次走一步,另外一个每次走2步。如果两者相遇,则有圈,否则没有圈

Java code
public boolean hasCycle(ListNode head) {
        ListNode p = head;
        ListNode pn = head;
        
        while(p != null && pn != null && pn.next != null){
             p = p.next;
             pn = pn.next.next;
             
             if(p != null && p == pn) return true;
        }
        
        return false;
    }

No comments:

Post a Comment