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;
}