一.Linked List Cycle
Total Accepted: 85115 Total Submissions: 232388 Difficulty: Medium
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 || head->next==NULL){
return false;
}
ListNode *first =head;
ListNode *second = head;
while(first && second)
{
first = first->next;
second = second->next;
if(second){
second = second->next;
}
if(first==second){
return true;
}
}
return false;
}
};
Next challenges: (M) Linked List Cycle II
二.Linked List Cycle II
Total Accepted: 61662 Total Submissions: 196038 Difficulty: Medium
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
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:
ListNode *detectCycle(ListNode *head) {
ListNode* slow=head,*fast=head;
bool has_cycle = false;
while(slow && fast){
slow = slow->next;
fast = fast->next;
if(fast){
fast=fast->next;
}
if(slow == fast && slow){
has_cycle = true;
break;
}
}
ListNode* p = has_cycle ? head:NULL;
while(has_cycle && p!=slow){
p = p->next;
slow = slow->next;
}
return p;
}
};
参考: