141. Linked List Cycle (LL)

 1 class Solution {
 2     public boolean hasCycle(ListNode head) {
 3         if(head == null) return false;
 4         if(head.next == null) return false;
 5         ListNode node1 = head;
 6         ListNode node2 = head;
 7         while(node1.next != null) {
 8             node1 = node1.next;
 9             if(node2.next != null && node2.next.next != null) {
10                 node2 = node2.next.next;
11             }else {
12                 return false;
13             }
14             if(node1 == node2) {
15                 return true;
16             }
17         }
18         return false;
19     }
20 }

 一个快一个慢 要是重合了就有cycle

posted @ 2018-08-17 23:34  jasoncool1  阅读(112)  评论(0编辑  收藏  举报