leetcode Linked List Cycle & Linked List Cycle II

来源:互联网 发布:雷云mac版安装失败 编辑:程序博客网 时间:2024/04/30 22:28

Linked List Cycle 要判断链表是否有环,通过设置快慢两个指针,慢的指针没走一步快的指针走两步,这样,如果有环,两个指针必然会相遇,否则,快的指针直到链尾就表示无环,这是因为对于一个链有环,由于快指针经环会绕道慢指针的后面,而每一步快指针都比慢指针快一步,二者最终必然相遇

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

Linked List Cycle II 需要在判断有环的基础上继续求得环的开始位置,只需要在快慢指针相遇后,将慢指针移到连头,两个指针同时一步一步后移,当二者再次相遇,即可找到环的开始位置 

  bool hasCycle(ListNode *head) {        if(head==NULL||head->next==NULL)return false;        ListNode *p=head,*q=head;        while(p&&p->next){            q=q->next;            p=p->next->next;            if(p==q)return true;        }    return !(p==NULL||p->next==NULL);            }class Solution {public:    ListNode *detectCycle(ListNode *head) {        //if(head==NULL||head->next==NULL)return NULL;        if(!hasCycle(head))return NULL;        ListNode *p=head,*q=head;        int i=0;        while(p&&p->next){            i++;            q=q->next;            p=p->next->next;            if(p==q)break;                    }        q=head;        while(p!=q){q=q->next;p=p->next;}        return q;            }};


0 0