標籤:style color io ar for sp on c amp
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) {} * }; */struct ListNode{int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};/*三種情況:1.head == null,返回false2.List只有一個結點,返回false3.這種情況,要用兩個指標,fast,slow.分別遍曆list,因為,fast比slow快兩倍,所以,找到list的cycle應該是可行的。當fast == slow的時候就可以判斷存在list的cycle,並且返回true,如果,遍曆結束,也沒有找到,那麼就返回false.*/class Solution {public: bool hasCycle(ListNode *head) {if(head == NULL) return false;if(head->next == NULL) return true;ListNode *fast = head->next;ListNode *slow = head;while(fast != NULL && fast->next != NULL){if(fast == slow || fast->next == slow){return true;}slow = slow->next;fast = fast->next->next;}return false; }};
leetcode - Linked List Cycle