141. Linked List Cycle
Given A linked list, determine if it has a cycle in it.
/*** Definition for singly-linked list. * Class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * next = NULL; * } * } */ Public classSolution { Public Booleanhascycle (ListNode head) {if(Head = =NULL|| Head.next = =NULL) return false; ListNode Slow=Head; ListNode Fast=Head; while(Fast.next! =NULL&& Fast.next.next! =NULL) {Slow=Slow.next; Fast=Fast.next.next; if(Slow = =fast)return true; } return false; }}
142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If There is no cycle, return null .
Note:do not modify the linked list.
/*** Definition for singly-linked list. * Class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * next = NULL; * } * } */ Public classSolution { PublicListNode detectcycle (ListNode head) {if(Head = =NULL|| Head.next = =NULL) return NULL; ListNode Slow=Head; ListNode Fast=Head; while(Fast.next! =NULL&& Fast.next.next! =NULL) {Slow=Slow.next; Fast=Fast.next.next; if(Slow = =fast) Break; } if(Fast.next = =NULL|| Fast.next.next = =NULL) return NULL; ListNode l=Head; while(L! =slow) {L=L.next; Slow=Slow.next; } returnl; }}
141. Linked List Cycle && 142. Linked List Cycle II