1 //public class ListNode { 2 // int val; 3 // ListNode next; 4 //} 5 6 public class ListNodeMeet { 7 8 public static ListNode enterNode(ListNode head){ 9 if(nodesInCycle(head) == 0){ 10 return null; 11 } 12 else{ 13 int nums = nodesInCycle(head); 14 ListNode slow = head; 15 ListNode fast = head; 16 for(int i = 0; i < nums; i++){ 17 fast = fast.next; 18 } 19 while(slow != fast){ 20 slow = slow.next; 21 fast = fast.next; 22 } 23 return slow; 24 } 25 } 26 27 public static int nodesInCycle(ListNode head){ 28 if(!hasCycle(head)){ 29 return 0; 30 } 31 else{ 32 ListNode slow = head; 33 ListNode fast = head; 34 while(true){ 35 if(slow.next == fast.next.next){ 36 ListNode meet = slow.next; 37 ListNode cur = slow.next.next; 38 int count = 1; 39 while(cur != meet){ 40 count++; 41 cur = cur.next; 42 } 43 return count; 44 } 45 slow = slow.next; 46 fast = fast.next.next; 47 } 48 } 49 } 50 51 public static boolean hasCycle(ListNode head){ 52 53 if(head == null){ 54 return false; 55 } 56 57 ListNode slow = head; 58 ListNode fast = head; 59 60 while(true){ 61 if(slow.next == null || fast.next.next == null){ 62 return false; 63 } 64 if(slow.next == fast.next.next){ 65 return true; 66 } 67 slow = slow.next; 68 fast = fast.next.next; 69 } 70 } 71 72 public static void main(String[] args) { 73 ListNode node1 = new ListNode(); 74 ListNode node2 = new ListNode(); 75 ListNode node3 = new ListNode(); 76 ListNode node4 = new ListNode(); 77 ListNode node5 = new ListNode(); 78 ListNode node6 = new ListNode(); 79 80 node1.val = 1; 81 node2.val = 2; 82 node3.val = 3; 83 node4.val = 4; 84 node5.val = 5; 85 node6.val = 6; 86 87 node1.next = node2; 88 node2.next = node3; 89 node3.next = node4; 90 node4.next = node5; 91 node5.next = node6; 92 node6.next = node3; 93 //node6.next = null; 94 95 System.out.println("是否有环: "+hasCycle(node1)); 96 System.out.println("环中节点个数: "+nodesInCycle(node1)); 97 System.out.println("环的入口节点: "+enterNode(node1)); 98 99 } 100 101 }
原文:http://www.cnblogs.com/spyder13/p/6547778.html