Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Two solutions:
1. o(n) solution
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
unordered_set<ListNode *> visited;
while (head != NULL) {
if(visited.find(head) != visited.end()) {
return true;
} else {
visited.insert(head);
}
head = head->next;
}
return false;
}
};
2. o(1) Solution: Use two pointers, one steps forward one node at a time, the other steps forward two nodes at a time. If a cycle exists, these two eventually will meet.
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 *single_forward = head, *double_forward = head;
while (double_forward != NULL) {
single_forward = single_forward->next;
double_forward = double_forward->next == NULL ?
double_forward->next : double_forward->next->next;
if (double_forward != NULL && single_forward == double_forward) {
return true;
}
}
return false;
}
};
No comments:
Post a Comment