[LeetCode] Linked List Cycle

Source: Internet
Author: User

[LeetCode] Linked List Cycle

 

Linked List Cycle

 

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

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

Solution:

1. The most basic method is to use a set to store all existing pointers. If a duplicate occurs, a ring exists. If no duplicate exists, no ring exists.

 

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    bool hasCycle(ListNode *head) {        ListNode* p = head;        set
 
   s;        while(p!=NULL){            if(s.find(p)!=s.end()){                return true;            }            s.insert(p);            p=p->next;        }        return false;    }};
 
2. Double pointer method. Set two pointers. one pointer takes one step at a time and the other pointer takes two steps at a time. If two pointers meet each other, a ring exists. If you do not meet each other, it indicates that there is no ring. See specific: http://blog.csdn.net/kangrydotnet/article/details/45154927

 

 

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    bool hasCycle(ListNode *head) {        ListNode* one = head;        ListNode* two = head;        while(two!=NULL && two->next!=NULL){            one=one->next;            two=two->next->next;            if(one==two){                return true;            }        }        return false;    }};



 

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.