Given a linked list, return the node where the cycle begins. If There is no cycle, return null .
Follow up:
Can you solve it without using extra space?
/*** Definition for singly-linked list. * Class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * next = NULL; * } * } */ Public classSolution { PublicListNode detectcycle (ListNode head) {ListNode fast=Head; ListNode Slow=Head; while(fast!=NULL&&fast.next!=NULL) {Slow=Slow.next; Fast=Fast.next.next; if(Slow==fast) Break; } if(fast==NULL|| fast.next==NULL){ return NULL; } Fast=Head; while(fast!=slow) {Fast=Fast.next; Slow=Slow.next; } returnFast; } /*ListNode Fast=head; ListNode Slow=head; if (head==null| | Head.next==null) return null; while (fast!=null) {slow=slow.next; if (fast.next!=null) {fast=fast.next.next; }else return null; if (slow==fast) break; } if (slow==fast) {fast=head; while (Fast!=slow) {fast=fast.next; Slow=slow.next; } return fast; } return null; }*/}
Linked List Cycle II