首页 > 技术文章 > 102. Linked List Cycle【medium】

abc-begin 2017-12-31 16:24 原文

Example

Given -21->10->4->5, tail connects to node index 1, return true

Challenge Follow up:
Can you solve it without using extra space?

 

解法一:

 1 class Solution {
 2 public:
 3     /**
 4      * @param head: The first node of linked list.
 5      * @return: True if it has a cycle, or false
 6      */
 7     bool hasCycle(ListNode *head) {
 8         ListNode * fast, * slow;
 9         if (head == NULL) {
10             return false;
11         }
12         slow = head;
13         fast = head->next;
14         
15         while (fast != NULL && fast->next != NULL) {
16             if (slow == fast) {
17                 return true;
18             }
19             slow = slow->next;
20             fast = fast->next->next;
21         }
22         
23         return false;
24     }
25 };

 

推荐阅读