链表中环的入口结点

题目:

如果一个链表中包含环,如何找到环的入口节点?

 

解答:

 1 public class Solution {
 2 
 3     public static ListNode meetingNode(ListNode head) {
 4         if(head == null) {
 5             return null;
 6         }
 7 
 8         ListNode pSlow = head.next;
 9         if(pSlow == null) {
10             return null;
11         }
12 
13         ListNode pFast = pSlow.next;
14         while(pFast != null && pSlow != null) {
15             if(pFast == pSlow) {
16                 return pSLow;
17             }
18 
19             pSlow = pSlow.next;
20             pFast = pFast.next;
21             if(pFast.next != null) {
22                 pFast = pFast.next;
23             }
24         }
25 
26         return null;
27     }
28 
29     public static ListNode entryNodeOfLoop(ListNode head) {
30         ListNode meetingNode = meetingNode(head);
31         if(meetingNode == null) {
32             return null;
33         }
34 
35         // 环中的节点的数目
36         int nodeInLoop = 1;
37         ListNode tmp = meetingNode;
38         while(tmp.next != meetingNode) {
39             tmp = tmp.next;
40             nodeInLoop++;
41         }
42 
43         // 先移动pNode1
44         ListNode pNode1 = head;
45         for(int i = 0; i < nodeInLoop; i++) {
46             pNode1 = pNode1.next;
47         }
48 
49         ListNode pNode2 = head;
50         while(pNode1 != pNode2) {
51             pNode1 = pNode1.next;
52             pNode2 = pNode2.next;
53         }
54 
55         return pNode1;
56     }
57 }

 

posted @ 2019-03-03 15:03  林木声  阅读(132)  评论(0编辑  收藏  举报