Given a linked list, determine if it has a cycle in it.spa
Follow up:
Can you solve it without using extra space?指針
注意,鏈表循環並非尾指針和頭指針相同,多是在中間某一段造成一個環路,因此不能只判斷元素和第一個元素是否存在重合code
先設置兩個指針p_fast和p_slow。從頭開始遍歷鏈表,p_fast每次走兩個節點,而p_slow每次走一個節點,若存在循環,這兩個指針一定重合:blog
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 bool hasCycle(ListNode *head) { 12 if(head == NULL) return false; 13 14 ListNode *p_fast = head; 15 ListNode *p_slow = head; 16 17 do{ 18 p_slow = p_slow->next; 19 if(p_fast != NULL) 20 p_fast = p_fast->next; 21 if(p_fast != NULL) 22 p_fast = p_fast->next; 23 else 24 return false; 25 }while(p_fast != p_slow); 26 27 return true; 28 29 } 30 };