题解 | #寻找链表中环的入口#

链表中环的入口结点

http://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4

// public class ListNode { int val; ListNode next = null;

ListNode(int val) {
    this.val = val;
}

} */ //快慢索引,具体见下图 alt public class Solution {

public ListNode EntryNodeOfLoop(ListNode pHead) {
    ListNode low = pHead;
    ListNode fast = pHead;
   if(pHead == null ) {//链表为空直接返回
       return null;
   }else{
       low = low.next;//慢索引先走一步
       if(low == null) return null;//为空返回
        fast = fast.next;//快索引走一步
        if(fast == null) return null;//为空返回
        fast = fast.next;//快索引再走一步
       if(fast == null) return null;//为空返回
       
      //找到第一次相遇的节点
       while(low != fast ){
         low = low.next;//慢索引先走一步
       if(low == null) return null;//为空返回
        fast = fast.next;//快索引走一步
        if(fast == null) return null;//为空返回
        fast = fast.next;//快索引再走一步
       if(fast == null) return null;//为空返回
    }
   }    
  //第一次相遇之后,快慢索引同速同步运动,慢索引返回头部重新开始运动
    //快索引从相遇节点运动
    //两个索引节点再次相遇时就是链表中环的入口
        low = pHead;
        while(low != fast){
        low = low.next;
        fast = fast.next;          
    }                                      
    return low;
}

} public class ListNode { int val; ListNode next = null;

ListNode(int val) {
    this.val = val;
}

} */ public class Solution {

public ListNode EntryNodeOfLoop(ListNode pHead) {
    ListNode low = pHead;
    ListNode fast = pHead;
   if(pHead == null ) {
       return null;
   }else{
       low = low.next;
       if(low == null) return null;
        fast = fast.next;
        if(fast == null) return null;
        fast = fast.next;
       if(fast == null) return null;
       
      
       while(low != fast ){
        low = low.next;
       if(low == null) return null;
        fast = fast.next;
        if(fast == null) return null;
        fast = fast.next;
       if(fast == null) return null;
    }
   }    
  
        low = pHead;
        while(low != fast){
        low = low.next;
        fast = fast.next;          
    }                                      
    return low;
}

}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务