题目:141
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题目分析:
判断一个链表是否存在环,并且时间复杂度为O(1),考虑用两个指针,p和q,p指针一次走一步,q指针一次走两步,若存在环,那么p指针进入环后,可以看作是q指针追逐p,若存在环,则一定会相遇。
代码如下:
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *p=head;
if(p==NULL) return false;
ListNode *q=head;
while(true){
p=p->next;
if(p==NULL)
return false;
q=q->next;
if(q==NULL)
return false;
q=q->next;
if(q==NULL)
return false;
if(p==q)
return true;
}
}
}
题目:142
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?
题目分析:
找到链表中环的起点。依然使用双指针的方式,分析下相遇时两指针走过的长度:
p指针:A+B
q指针:A+B+C+B
且q的速度是p的二倍,则得到2(A+B)=A+B+C+B,得到A=C。
也就是说两指针相遇后,一个从起点head出发,一个从相遇点出发,每次走一步,走过C长度后都到达进入点。
代码如下:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *p=head;
if(p==NULL) return NULL;
ListNode *q=head;
while(true){
p=p->next;
if(p==NULL)
return NULL;
q=q->next;
if(q==NULL)
return NULL;
q=q->next;
if(q==NULL)
return NULL;
if(p==q)
break;
}
p=head;
while(p!=q){
p=p->next;
q=q->next;
}
return p;
}
}