This problem asks you to determine whether a singly linked list has a cycle, without using extra space.
At first I really didn’t know how to solve it, so I looked at other people’s solutions.
The idea is to use two pointers: one advances one step at a time, the other advances two steps. If they reach NULL without ever being equal, there is no cycle. If they become equal, a cycle exists.
Code below. I honestly feel my pointer and linked list skills are pretty weak.
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
| class Solution {
public:
bool hasCycle(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ListNode * step1 = head;
ListNode * step2 = head;
while(true)
{
if(step1 == NULL)
{
return false;
}
step1 = step1->next;
if(step2 == NULL || step2->next == NULL)
{
return false;
}
step2 = step2->next->next;
if(step1 == step2)
{
return true;
}
}
}
};
|