-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexe141
More file actions
32 lines (28 loc) · 863 Bytes
/
Copy pathexe141
File metadata and controls
32 lines (28 loc) · 863 Bytes
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
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
/**
* 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 *nextNode = head->next;
ListNode *doubleNextNode = head->next->next;
while(doubleNextNode!=NULL && doubleNextNode->next!=NULL && doubleNextNode->next->next!=NULL){
if(nextNode == doubleNextNode)
return true;
nextNode = nextNode->next;
doubleNextNode = doubleNextNode->next->next;
}
return false;
}
};