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.
1 public class Solution { 2 public boolean hasCycle(ListNode head) { 3 if(head==null || head.next==null) return false; 4 ListNode slower =head,faster = head; 5 while(faster!=null && faster.next!=null){ 6 if(faster==slower) return true; 7 faster = faster.next.next; 8 slower = slower.next; 9 } 10 return false; 11 } 12 }