已知一個(gè)鏈表的頭結(jié)點(diǎn)head,判斷鏈表中是否有環(huán)
思路:快慢指針。定義兩個(gè)指針,一個(gè)指針每次只移動(dòng)一步,另一個(gè)指針每次移動(dòng)兩步,如果是環(huán)形鏈表,兩個(gè)指針肯定會(huì)相遇,那么該鏈表就是環(huán)形鏈表;如果快速指針從頭結(jié)點(diǎn)一直到fast==NULL或者fast->next==NULL都沒有跟慢指針相遇,那么它就不是環(huán)形鏈表
#ifndef _HASCYCLE_H_#define _HASCYCLE_H_#define true 1#define false 0#include #include typedef int bool;struct ListNode { int val; struct ListNode* next;};bool hasCycle(struct ListNode* head);#endif//方法實(shí)現(xiàn)bool hasCycle(struct ListNode* head) { if(head == NULL || head->next == NULL) return false; struct ListNode* fast = head; struct ListNode* slow = head; do { if (fast == NULL || fast->next == NULL) return false; fast = fast->next->next; slow = slow->next; } while (fast != slow); return true;}