-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path141.cpp
55 lines (52 loc) · 1.14 KB
/
141.cpp
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
* 需要O(1) 空间
*/
/**
* 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) return false;
ListNode *end = new ListNode(0), *now = head, *tem = head;
while(now != NULL && now != end)
{
tem = now->next;
now->next = end;
now = tem;
}
return now == NULL ? false : true;
}
};
/*
* 不需要额外空间
*/
/**
* 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) return false;
ListNode *first = head, *second = head;
while(first != NULL && second != NULL)
{
first = first->next;
if(first == NULL) break;
first = first->next;
second = second->next;
if(first == second) return true;
}
return false;
}
};