142 Linked List Cycle II (if the linked list has loops, find the entry node)

Source: Internet
Author: User

Title meaning: If there is a ring, return to the entry node.

Idea: First judge have no ring, and then calculate the knot number of the ring, then P1 point to the head, P2 back to the node, p1, p2 meet for the entrance node

PS: or the idea of using the pointer spacing

1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7  * };8  */9 classSolution {Ten  Public: OneListNode *detectcycle (ListNode *head) { A         if(Head==null)returnNULL; -ListNode *p1,*P2; -P1=p2=head; the         intn=1; -          while(p2->next&&p2->next->next) { -P1=p1->Next; -P2=p2->next->Next; +             if(p1==p2) { -                  while(p1->next!=p2) { +P1=p1->Next; A++N; at                 } -P1=p2=head; -                  while(n--){ -P2=p2->Next; -                 } -                  while(true){ in                     if(P1==P2)returnP1; -P1=p1->Next; toP2=p2->Next; +                 } -             } the         } *         returnNULL; $     }Panax Notoginseng};

142 Linked List Cycle II (if the linked list has loops, find the entry node)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.