LeetCode 142: Linked List Cycle II 输出链表中环的起点

问题: Given a linked list, return the node where the cycle begins. If there is no cycle, return  null .

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

题意:判断一个链表中是否存在环,如果存在,返回这个环的起点,如果不存在,请返回null。

问题分析:

1.首先如何判断一个链表中存在一个环呢?

定义两个指针,fast和slow,其中fast每次跳两个节点,而slow每次跳一个节点。如果fast碰到null,说明此链表无环,如果遇到fast==slow的情况,说明链表中存在环。因为在环形结构中,fast指针移动超越了slow指针一段距离,而这种情况,在无环情况下是不存在的。这就好比,一条笔直的路,跑的快的永远在跑的慢的前面,如果是一个圈,那跑得快的一定会超越跑的慢的一圈,两圈,三圈。。。


2.如何找到环的起点


如何,X为链表的起点,Y为环的起点,而Z为fast和slow相遇的地方。

当slow走到Z时,它所走过的距离为(a+b),而当fast再次走到Z时,他所走过的距离为(a+b+c+b),因为fast的速度是slow的两倍,所以有

2*(a+b) = a+b+c+b,由此我们可以推断出,a=c。

这个题的经典思路:

当fast和slow相遇时,此时重新定义一个指针从X位置开始移动,slow从Z开始移动,直到两个指针相遇,因为a=c,所以两个指针相遇的地方就是环开始的地方。

代码如下:

 public ListNode detectCycle(ListNode head) {
                ListNode slow = head;
                ListNode fast = head;
        
                while (fast!=null && fast.next!=null){
                    fast = fast.next.next;
                    slow = slow.next;
                    
                    if (fast == slow){			//fast和slow相遇了
                        ListNode slow2 = head; 
                        while (slow2 != slow){		//两个节点分别从相遇点和头结点出发
                            slow = slow.next;
                            slow2 = slow2.next;
                        }
                        return slow;
                    }
                }
                return null;
            }




猜你喜欢

转载自blog.csdn.net/VP_19951105/article/details/70135914
今日推荐