LeetCode OJ: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?
判断一个链表是否存在环,维护快慢指针就可以,如果有环那么快指针一定会追上慢指针,代码如下:
1 class Solution { 2 public: 3 bool hasCycle(ListNode *head) { 4 ListNode * slow, * fast; 5 slow = fast = head; 6 while(slow && fast){ 7 slow = slow->next; 8 fast = fast->next; 9 if(fast) fast = fast->next; 10 if(fast && slow && slow == fast) 11 return true; 12 } 13 return false; 14 } 15 };