Linked List Cycle
Problem:
Given A linked list, determine if it has a cycle in it.
Ideas:
Fast pointer, slow pointer method
My Code:
Public classSolution { Public Booleanhascycle (ListNode head) {if(Head = =NULL|| Head.next = =NULL) return false ; ListNode One=Head; ListNode=Head.next.next; while(One! =NULL&& both! =NULL) { if(One = =Both )return true ; One=One.next; if(Two.next = =NULL) Break ; both=Two.next.next; } return false ; }}View Code
Others code:
Public classSolution { Public Booleanhascycle (ListNode head) {if(Head = =NULL) { return false; } ListNode Fast= Head, slow =Head; Do { if(Fast.next = =NULL|| Fast.next.next = =NULL) { return false; } Fast=Fast.next.next; Slow=Slow.next; } while(Fast! =slow); return true; }}View Code
The Learning Place:
- If there is no cycle, the fast pointer must go to NULL first
- The magic of doing while can be judged.
Linked List Cycle