[关闭]
@snuffles 2019-04-10T23:11:31.000000Z 字数 819 阅读 787

L142 环形链表 II

未分类


给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

解:快慢指针,head->环的起点+环的起点->相遇的点 = 环的长度。

  1. ListNode *detectCycle(ListNode *head) {
  2. ListNode * fast=head, * slow = head, *cur=head;
  3. // find meet point
  4. while(fast && fast->next){
  5. slow = slow->next;
  6. fast = fast->next->next;
  7. if(slow == fast) break;
  8. }
  9. // if not meet
  10. if(!fast || !fast->next) return NULL;
  11. // start from head and meetpoint,fast领先了的一圈,会在入环口第二次相遇
  12. slow = head;
  13. while(slow != fast){
  14. slow = slow->next;
  15. fast = fast->next;
  16. }
  17. return fast;
  18. }
  1. ListNode *detectCycle(ListNode *head) {
  2. if(head == NULL) return NULL;
  3. ListNode * fast = head;
  4. ListNode * slow = head;
  5. bool hascycle = false;
  6. while(fast!=NULL && fast->next!=NULL){
  7. slow = slow->next;
  8. fast = fast->next->next;
  9. if(slow == fast){
  10. hascycle = true;
  11. break;
  12. }
  13. }
  14. if(hascycle){
  15. slow = head;
  16. while(slow!=fast){
  17. slow=slow->next;
  18. fast = fast->next;
  19. }
  20. return slow;
  21. }
  22. else return NULL;
  23. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注