[LeedCode OJ] #141 Linked List Cycle,
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Link: https://leetcode.com/problems/linked-list-cycle/
Question:
Give a linked list and determine whether the linked list has loops.
Ideas:
Set the speed pointer. The speed pointer takes two steps at a time, and the slow pointer takes one step at a time. If the fast pointer reaches NULL, it indicates that there is no loop. Once the fast pointer is equal to the slow pointer, it indicates that there is a loop.
/** * 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) { if(head==NULL) return false; ListNode *fast,*slow; fast = slow = head->next; while(fast!=NULL&&fast->next!=NULL) { fast = fast->next->next; slow = slow->next; if(fast==slow) return true; } return false; }};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source