給定一個鏈表,判斷鏈表中是否有環。
為了表示給定鏈表中的環,我們使用整數 pos
來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos
是 -1
,則在該鏈表中沒有環。
可以用快慢指針的方法來解決該問題
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ bool hasCycle(struct ListNode *head) { struct ListNode *slow = NULL; struct ListNode *fast = NULL; if (head == NULL || head->next == NULL) return false; slow = head; fast = head; while(fast->next && fast->next->next){ slow = slow->next; fast = fast->next->next; if (slow == fast) return true; } return false; }