- class Solution { public boolean hasCycle(ListNode head) {
- if(head == null) return false;
- if(head.next == null) return false;
- ListNode node1 = head;
- ListNode node2 = head;
- while(node1.next != null) {
- node1 = node1.next;
- if(node2.next != null && node2.next.next != null) {
- node2 = node2.next.next;
- }else {
- return false;
- }
- if(node1 == node2) {
- return true;
- }
- }
- return false;
- }
- }
一个快一个慢 要是重合了就有 cycle
来源: http://www.bubuko.com/infodetail-2732022.html