已知一個鏈表的頭結(jié)點head,判斷鏈表中是否有環(huán)
思路:快慢指針。定義兩個指針,一個指針每次只移動一步,另一個指針每次移動兩步,如果是環(huán)形鏈表,兩個指針肯定會相遇,那么該鏈表就是環(huán)形鏈表;如果快速指針從頭結(jié)點一直到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//方法實現(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;}