"Linked List Cycle" cpp

Source: Internet
Author: User

title :

Given A linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

Code :

With version HashMap

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

Instead of HashMap, use the double-pointer skill version

/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public:    BOOLHascycle (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)return true; }            return false; }};

Tips:

Both of these solutions are basic techniques. The second double-pointer technique is more efficient and less space-complex, and seems to be more admired, but the individual always feels hashmap is good and does not rely on skill.

"Linked List Cycle" 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.