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?

刚开始没看见下面不用额外空间的话,用set搞了个:

public static boolean hasCycle(ListNode head){
ListNode p = head;
if(head == null)
return false;
Set set = new HashSet();

while(p.next != null){
set.add(p);
if(set.contains(p.next))
return true;
p = p.next;

}
return false;
}


后来在逛discuss时候,发现了without using extra space,看了下别人的解法,用快慢两个指针,比自己想的两层循环好多了

bool hasCycle(ListNode *head) {
        ListNode *slow_ptr = head, *fast_ptr = head;
        while(slow_ptr != NULL && fast_ptr != NULL && fast_ptr->next != NULL)
        {
          slow_ptr = slow_ptr->next;
          fast_ptr = fast_ptr->next->next;
          if(slow_ptr == fast_ptr)
            return true;
        }
        return false;
    }

你可能感兴趣的:(LeetCode)