Linked List cyclegiven a linked list, determine if it has a cycle in it.
C ++
/*** 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) {/* 1. empty linked list is not a ring 2. one node self-ring 3. A linked list is complete into a ring */If (Head = NULL) return false; If (Head-> next = head) return true; listnode * Y = head-> next; listnode * x = head-> next; while (X! = NULL & Y! = NULL) {x = x-> next; If (x = NULL) break; X = x-> next; y = Y-> next; if (x = y) break;} return x = y ;}};
Java version:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * * **/ public class Solution {public boolean hasCycle(ListNode head) {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;}}
Linked List cycle