-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinked_List_Cycle.cpp
More file actions
52 lines (47 loc) · 1.32 KB
/
Linked_List_Cycle.cpp
File metadata and controls
52 lines (47 loc) · 1.32 KB
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
// Source : https://leetcode-cn.com/problems/linked-list-cycle/description/
// Number : 141
// Author : HL
// Date : 2018-09-03
// Kill : 98.85%,37.14%
/**********************************************************************************
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
**********************************************************************************/
/**
* 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 *p = head;
// ListNode *q = p->next;
// while(q != p){
// if(q == NULL || q->next == NULL)
// return false;
// p = p->next;
// q = q->next->next;
// }
// return true;
// 哈希解法
map<ListNode*,ListNode*> mp;
ListNode *p = head;
while(p != NULL){
if(mp.find(p->next) != mp.end())
return true;
else{
mp[p] = p->next;
p = p->next;
}
}
return false;
}
};