Given a linked list, determine if it has a cycle in it.
想法:使用两个指针,一个指针每次指向当前节点的下下节点,称为快指针,另外一个指针每次指向当前节点的下一个节点,称为慢指针。如果链表成环的话,则快指针和慢指针将会相遇。否则就不存在环
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ bool hasCycle(struct ListNode *head) { if(head == NULL ){ return false; } struct ListNode* slow = head; struct ListNode* fast = head; while( fast->next != NULL && fast->next->next != NULL){ slow = slow->next; fast = fast->next->next; if(slow == fast){ return true; } } return false; }