题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解析:
1 class Solution { 2 public: 3 bool hasCycle(ListNode *head) { 4 ListNode* slow = head; 5 ListNode* fast = head; 6 while (fast && fast->next){ 7 fast = fast->next->next; 8 slow = slow->next; 9 if (slow == fast) 10 return true; 11 } 12 return false; 13 } 14 };
注意:开始while的判断语句写成了
fast->next && fast
这是万万不可的,因为&&运算首先要判断前者,万一fast不存在,判断fast->next将会超时