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?

判断一个链表是否有环

C++(10ms):

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         if (head == NULL)
13             return false ;
14         ListNode* runner = head ; 
15         ListNode* walker = head ; 
16         while(runner->next != NULL && runner->next->next != NULL ){
17             walker = walker->next ;
18             runner = runner->next->next ;
19             if (runner == walker)
20                 return true ;
21         }
22         return false ;
23     }
24 };
原文地址:https://www.cnblogs.com/mengchunchen/p/8287274.html