标签:style blog color 使用 io div amp log
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:使用两个指针slow和fast,分别以1和2的速度遍历链表。若链表中存在环,则两个指针必然会在某时刻相遇。
1 class Solution { 2 public: 3 bool hasCycle(ListNode *head) { 4 if( !head || !head->next ) { return false; } 5 ListNode *slow = head, *fast = head; 6 while( fast ) { 7 slow = slow->next; 8 fast = fast->next; 9 if( fast ) { fast = fast->next; } 10 if( fast && fast == slow ) { return true; } 11 } 12 return false; 13 } 14 };
Linked List Cycle,布布扣,bubuko.com
标签:style blog color 使用 io div amp log
原文地址:http://www.cnblogs.com/moderate-fish/p/3905264.html