Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
设两个指向输入链表的指针,walker和runner,制造一个while函数,一次循环walker指向下一个链表,runner指向下下个链表,如果输入链表是一个环,那么walker和runner总有相遇的一次,如果它们指向同一个链表中的元素,那么返还true,如果链表有结束的节点,则返还false。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
if(head==NULL)
return false;
struct ListNode *walker=head;
struct ListNode *runner=head;
while(head->next!=NULL && head->next->next!=NULL){
walker=head->next;
runner=head->next->next->next;
if(walker==runner)
return true;
}
return false;
}