剑指offer--链表中环的入口结点

来源:互联网 发布:透视内裤软件 编辑:程序博客网 时间:2024/06/03 16:34

题目描述

一个链表中包含环,请找出该链表的环的入口结点。
分析:

如果存在环,找到环的起始结点

当fast指针等于slow指针时,slow指针肯定还没有遍历完整个链表,而此时fast指针已经在环内循环了n圈(n>=1),假定从链表头指针开始slow走了s步,则fast走了2s步,fast所走的步数还等于s加上fast指针比slow指针在环内多走的n圈。设环长为r,则:

2s = s + nr;

=>s = nr;

设整个链表长度为L,环的入口结点到相遇结点的距离为x, 起点到环的入口结点的距离为a.

a + x = nr;

=> a + x = (n-1)r + L - a;

=> a = (n-1)r + (L - a - x);

=> 由链表的头结点到环入口结点的距离等于n-1圈环的长度+相遇点到环入口结点的距离,于是,当我们在链表头部和相遇处分别设一指针,每次各走一步,则两指针必定相遇,且相遇的第一个结点即为环的入口结点

[java] view plain copy
  1. /* 
  2.  public class ListNode { 
  3.     int val; 
  4.     ListNode next = null; 
  5.  
  6.     ListNode(int val) { 
  7.         this.val = val; 
  8.     } 
  9. } 
  10. */  
  11. public class Solution {  
  12.   
  13.     ListNode EntryNodeOfLoop(ListNode pHead)  
  14.     {  
  15.         if (pHead == null || pHead.next == null) {  
  16.              return null;  
  17.          }  
  18.          ListNode fast = new ListNode(0);  
  19.          ListNode slow = new ListNode(0);  
  20.          slow = pHead.next;  
  21.          fast = pHead.next.next;  
  22.          while (fast != slow) {  
  23.              slow = slow.next;  
  24.              fast = fast.next.next;  
  25.          }  
  26.          fast = pHead;  
  27.          while (fast != null) {  
  28.              if (fast == slow) {  
  29.                  return fast;  
  30.              }  
  31.              slow = slow.next;  
  32.              fast = fast.next;  
  33.          }  
  34.          return slow;  
  35.     }  
  36. }  
转自:http://blog.csdn.net/crazy__chen/article/details/45100007
原创粉丝点击