leetcode Linked List Cycle II

来源:互联网 发布:sim卡网络注册失败 编辑:程序博客网 时间:2024/05/16 16:20

问题:Given a linked list, return the node where the cycle begins. If there is no cycle, return null

解决:快慢指针,判断是否有环,然后找进入环的节点


假设在Z点相遇,则快指针走了a+b+c+b,慢指针走了a+b,又因为快指针走了慢指针的两倍,所以2(a+b)=a+b+c+b,推出a=c,所以相遇之后让一个指针从z点出发,另外一个指针从X点出发,每次走一步,相遇的点就是Y点,代码如下

 struct ListNode {     int val;     ListNode *next;     ListNode(int x) : val(x), next(NULL) {} }; class Solution {public:    ListNode *detectCycle(ListNode *head) {        ListNode *fastp = head, *slowp = head;        while(1){            if(fastp == NULL ||fastp->next == NULL) return NULL;            fastp = fastp->next->next;            slowp = slowp->next;            if(slowp == fastp)  break;        }        slowp = head;        while(slowp != fastp){            slowp = slowp->next;            fastp = fastp->next;        }        return slowp;    }};

0 0
原创粉丝点击