您的位置:首页 > 其它

142. Linked List Cycle II

2016-05-09 22:52 357 查看
先看141. Linked List Cycle 。

Given a linked list, determine if it has a cycle in it.

判断链表是否有环,用两个快慢指针移动看是否重合即可。

class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *first=head,*sec=head;
while(first!=NULL&&sec!=NULL&&sec->next!=NULL){
first=first->next;
sec=sec->next->next;
if(first==sec)
return true;
}
return false;
}
};


题目142,不仅需要判断是否有环,还需要求环的入口结点。

如果允许使用额外的空间的话。

class Solution {
public:
ListNode *detectCycle(ListNode *head) {
map<ListNode*,bool>;
while(head!=NULL){
if(v[head]==true)
return head;
v[head]=true;
head=head->next;
}
return NULL;
}
};


如果不用额外空间的话,同样需要两个指针。

当快慢指针相遇时,把快指针设置为头结点,

然后快慢指针都每次向前走一步,相遇时即为环的入口。

class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *first=head,*sec=head;
int fla=1;
while(first!=NULL&&sec!=NULL&&sec->next!=NULL){
first=first->next;
sec=sec->next->next;
if(first==sec){
fla=0;
break;
}
}
if(fla)
return NULL;
sec=head;
while(sec!=NULL&&first!=NULL){
if(sec==first)break;
sec=sec->next;
first=first->next;
}
return first;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: