0%

判断链表是否有环

1
2
3
4
Given a linked list, determine if it has a cycle in it.

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

可以使用快慢指针判断,快指针每次走两步,慢指针每次走一步
如果有环的话快慢指针一定会相遇,注意判断指针是否为空

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
28
29
30
31
32
33
/**
* 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) {
ListNode *fast, *slow;

fast = slow = head;

while (fast && slow) {
fast = fast->next;

if (fast == NULL) {
return false;
}

fast = fast->next;
slow = slow->next;

if (fast == slow) {
return true;
}
}

return false;
}
};