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

题目描述

给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

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

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {

    public ListNode EntryNodeOfLoop(ListNode pHead)
    {
        if(pHead==null||pHead.next==null){
            return null;
        }
        ListNode first=pHead,second=pHead.next,middle=null;
        while(first!=null&&second!=null){
            if(first==second){
                middle=first;
                break;
            }
            first=first.next;
            second=second.next;
            if(first!=second){
                second=second.next;
            }
        }
        ListNode temp = middle;
        int step=0;
        while(temp.next!=middle){
            temp=temp.next;
            step++;
        }
        step++;
        first=pHead;
        second=pHead;
        for(int i=0;i<step;i++){
            second=second.next;
        }
        while(first!=second){
            first = first.next;
            second = second.next;
        }
        return first;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_27378875/article/details/81363029