题干
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
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) {}
* };
*/
解题思路
1.有额外空间的话是可以用vector等数据结构,遍历结点,遍历结点的时候存储访问过的结点,用O(1)的时间可以检索是否已经存储过相同结点。如果有相同结点,便得到了入口结点;如果没找到,便添加当前结点到vector中。
2.没有空间开销的方法分几步:
a.判断链表是否有环:用两个指针,一慢p1一快p2,遍历链表,如果两个指针相遇,则说明有环。
b.得到环中结点的数量:a步当中相遇的快慢指针位置,一个指针固定p2,另一个p1以步长为1继续遍历,并计数,再次相遇得到环中结点的数量cyc_num。
c.得到环入口结点:置p1,p2两指针为头结点head,先让p2结点向后走cyc_num步,然后p1,p2一起以步长为1遍历链表。相遇得到的结点即为入口结点。
参考代码
方法一:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head==NULL) return NULL;
ListNode *cur=head;
vector<ListNode *>data;//建立vector以存储经过的结点
while(cur->next!=NULL){
vector<ListNode *>::iterator s=find(data.begin(),data.end(),cur);//O(1)时间查找,是否存储过当前结点
if (s!=data.end())//存储过当前结点
return cur;
data.push_back(cur);//添加结点到vector中
cur=cur->next;
}
return NULL;
}
};
方法二:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head==NULL) return NULL;
ListNode *p1=head,*p2=head;
int cyc_num=1;
//第一步:判断是否存在环
while(p2->next!=NULL&&p2->next->next!=NULL){
p1=p1->next;//步长为1
p2=p2->next->next;//步长为2
if (p1==p2){//如果存在环
//第二步:确定环中结点数量
while(p1->next!=p2){
p1=p1->next;
cyc_num++;
}
//第三步:找到入口结点
p1=head;p2=head;
for(int i=0;i<cyc_num;i++)
p2=p2->next;
while(p1!=p2){
p1=p1->next;
p2=p2->next;
}
return p1;
}
}
return NULL;
}
};
方法讨论
方法1代码简单但需要额外开销。
方法2代码相对复杂但是没有额外的空间开销。
综上两个方法应用场景不同,所以各有用处。