141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
利用快慢指针,如果相遇则证明有环
注意边界条件: 如果只有一个node.
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null || head.next==null) return false;
ListNode slower =head,faster = head;
while(faster!=null && faster.next!=null){
if(faster==slower) return true;
faster = faster.next.next;
slower = slower.next;
}
return false;
}
}