141. Linked List Cycle(判断链表是否有环)

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 }
 
原文地址:https://www.cnblogs.com/zle1992/p/7569489.html