leetcode-141-链表题-环形链表

题目

1.png

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/

// 快慢指针
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head) return false;

ListNode *slow = head;
ListNode *fast = head->next;

while(fast && fast->next){
if(slow == fast) return true;
slow = slow->next;
fast = fast->next->next;
}

return false;
}
};