[LeetCode]Linked List Cycle

来源:互联网 发布:网络教育介绍 编辑:程序博客网 时间:2024/06/06 23:37

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

Analysis:

two pointers.
One pointer is slow (1 step a time)
One pointer is fast (2 steps a time)
If there is a cycle, the two pointers will eventually meet (equal).

java

public boolean hasCycle(ListNode head){if(head == null || head.next == null) return false;ListNode p1 = head;ListNode p2 = head;while(p1!=null){p1 = p1.next;if(p2.next!=null)p2 = p2.next.next;else return false;if(p1 == p2)return true;}return false;}

c++

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


0 0