141. Linked List Cycle
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 *slow,*fast; if(NULL == head || NULL == head->next) return false; slow = head; fast = head; fast = fast->next->next; slow = slow->next; while(1) { if(fast == NULL || fast->next == NULL) return false; if(fast == slow || fast->next == slow) return true; slow = slow->next; fast = fast->next->next; } return false; } };
總結:快慢指針
快慢指針中的快慢指的是移動的步長,即每次向前移動速度的快慢。例如可以讓快指針每次沿鏈表向前移動2,慢指針每次向前移動1次。
快慢指針可以用來求一個單鏈表是否存在環,還可以用來求一個單鏈表的中間位置。
2016-08-13 00:34:46