LeetCode-Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
首先确定是否有环,并找到环上一点,通过该点得到环的长度,用两个差为环长度的指针来探测环的起点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *detectCycle(ListNode *head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ListNode * p1=head,*p2=head; ListNode * pic,*ptr; if(head==NULL)return NULL; int length=1;//length of the circle while(true){ p1=p1->next; if(p1==NULL)return NULL; p2=p2->next; if(p2==NULL)return NULL; p2=p2->next; if(p2==NULL)return NULL; if(p1==p2){ pic=p1; ptr=p2; break; } } while(ptr->next!=pic){ length++; ptr=ptr->next; } if(length==1)return pic; p1=head; for(int i=0;i<length;i++){ p1=p1->next; } p2=head; while(p1!=p2){ p1=p1->next; p2=p2->next; } return p1; } };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步