Topic:
Given A linked list, determine if it has a cycle in it.
Thinking Analysis:
Use the fast and slow pointer slow,fast. Slow hands each step, fast hands each step two steps, if there is a ring, then slow and fast must meet at a certain moment.
C + + Reference code:
/** * 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) return false ; ListNode *slow = head; ListNode *fast = head->next; while (Fast && Fast->next) {if (slow = = fast) return true ; slow = slow->next; Fast = fast->next->next; } return false ; }};
Another way to do this:
class solution {Public :BOOL Hascycle (ListNode*head) {if(!head)return false;ListNode*slow = head;ListNode*fast = head; while(Fast && fast->Next) {slow = slow->Next; Fast = Fast->Next-Next;if(slow = = fast)return true; }return false; }};
C # Reference Code:
/** * Definition for singly-linked list. * public class ListNode {* public int val, * public ListNode next; public ListNode (int x) {* val = x; * next = NULL; *} *} */ Public class solution{ Publicboolhascycle(ListNode head) {if(Head = =NULL)return false; ListNode slow = head; ListNode fast = head; while(Fast! =NULL&& Fast.next! =NULL) {slow = Slow.next; Fast = Fast.next.next;if(slow = = fast)return true; }return false; }}
leetcode:linked List Cycle