您的位置:首页 > 其它

141. Linked List Cycle 注意边界条件

2016-06-16 21:10 453 查看
Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

Subscribe to see which companies asked this question
这里要注意 边界条件由快那个指针确定  不用考虑慢那个  若只考虑快那个一次走两步的情况 那么 一次走两步若next为空 next->next则无法访问 

/**
* 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){
return false;
}
if(head->next == head){
return true;
}
ListNode*t1 = head;
ListNode*t2 = head;
//这里要注意 边界条件由快那个指针确定  不用考虑慢那个  若只考虑快那个一次走两步的情况 那么 一次走两步若next为空 next->next则无法访问
while(t2->next!=NULL&&t2->next->next!=NULL){
t1 = t1->next;
t2 = t2->next->next;
if(t1 == t2){
return true;
}
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: