"Linked List Cycle II" cpp

Source: Internet
Author: User

title :

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?

Code :

Using version HashMap

/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*detectcycle (ListNode *head) {Std::map<listnode *,BOOL>ifnodeoccured; ListNode*p =Head;  while(p) {if(Ifnodeoccured.find (p)! = Ifnodeoccured.end ())returnp; Ifnodeoccured.insert (std::p air<listnode *,BOOL> (P,true)); P= p->Next; }            returnNULL; }};

No HashMap version (O (1) space complexity)

/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*detectcycle (ListNode *head) {            if(!head)return false; ListNode*P1 =Head; ListNode*P2 =Head;  while(P2->next && p2->next->next) {P2= p2->next->Next; P1= p1->Next; if(p2==p1) {P1=Head;  while(P1! =p2) {P1= p1->Next; P2= p2->Next; }                    returnP1; }            }            return false; }};

Tips:

Individuals still like HashMap solution, because more unified, but when the amount of data is very large, the opening up HashMap occupies a lot of resources.

The second solution refers to the following two logs:

Http://www.cnblogs.com/hiddenfox/p/3408931.html

http://blog.csdn.net/cs_guoxiaozhu/article/details/14209743

only the case with ring is discussed here:

Speed pointer skill; slow = = fast, then the distance is twice times the walking distance, let's slow down from the beginning, quickly from the meeting point, but each time to take a step, then meet again the place is the starting point.

This is a special skill, whether it is the head to meet the point how long, are satisfied. Still like the practice of HashMap.

"Linked List Cycle II" cpp

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.