Linked List cycle: determines whether a linked list has a loop)

Source: Internet
Author: User

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

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

Note: The linked list loop is not the same as the tail pointer and header pointer, but may form a loop in the middle section. Therefore, you cannot only determine whether the element and the first element overlap.

Set two pointers: p_fast and p_slow. From the beginning, in the traversal chain table, p_fast takes two nodes each time, while p_slow takes one node each time. If there is a loop, the two pointers must overlap:

 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 class Solution {10 public:11     bool hasCycle(ListNode *head) {12         if(head == NULL) return false;13         14         ListNode *p_fast = head;15         ListNode *p_slow = head;16         17         do{18             p_slow = p_slow->next;19             if(p_fast != NULL)20                 p_fast = p_fast->next;21             if(p_fast != NULL)22                 p_fast = p_fast->next;23             else24                 return false;25         }while(p_fast != p_slow);26         27         return true;28         29     }30 };

 

Linked List cycle: determines whether a linked list has a loop)

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.