環形鏈表
阿新 • • 發佈:2018-11-20
|| 說明 xtra fin 如果 slow head area turn
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
題意:判斷一個鏈表是否有環
思路:快慢指針,如果會相遇,則說明有環,如果快指針到了鏈表的末尾沒有相遇,則說明沒有環
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * };*/ class Solution { public: bool hasCycle(ListNode *head) { ListNode * fast; ListNode * slow; if(head==nullptr || head->next==nullptr) return false; //nullptr是c++11為了解決NULL可能被編譯為0這個問題,才有的,空指針 else{ fast=head; slow=head;while(fast->next!=nullptr && fast->next->next!=nullptr) { fast=fast->next->next; slow=slow->next; if(fast==slow) return true; } return false; } } };
環形鏈表