Fork me on GitHub

Linked List Cycle

Descripition

https://leetcode.com/problems/linked-list-cycle/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 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 == NULL || head->next == NULL) return false;
ListNode* before = head;
ListNode* after = head;
while (after != NULL) {
before = before->next;
after = after->next;
if (after == NULL) return false;
after = after->next;
if (before == after) return true;
}
return false;
}
};

1 - 2 - 3 - 4

​ \ /

​ 5 - 6

4步

1 - 2 - 3

​ 4 5

4步

1 2

3

3步

1 2

两部