您的位置:首页 > 理论基础 > 数据结构算法

leetcode 141.Linked List Cycle

2015-11-08 11:00 239 查看
思路:

快慢指针

n1每次递增为n1->next;

n2每次递增为n2->next->next;

如果n1==n2,那么说明有循环

PS:Linked List Cycle II应该会需要到这个解法。

/**
* 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) return false;
if(!head->next) return false;
ListNode* n1=head;
ListNode* n2=head->next;
while(n1){
if(n1==n2) return true;
if(n1->next){
n1=n1->next;
}else{
return false;
}
if(n2->next){
if(n2->next->next){
n2=n2->next->next;
}else{
return false;
}
}else{
return false;
}
}

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