说明:
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
不允许修改给定的链表。
思路:
- 首先,判断他是不是一个带环链表,如果是再求入环的第一个节点,如果不是,返回null
- 判断是不是环的方法:
定义一个快指针,一次走两步;定义一个慢指针,一次走一步,如果是环,他们一定会相遇;如果不是环,最后一个节点的next = 空
如果是环,求入环的第一个节点: - 在定义一个指针,从链表头开始走,另一个从快慢指针的交点开始走,两个指针都是一步一步的走,两个指针的交点就是入环的第一个节点
代码如下:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode Fast = head;
ListNode Slow = head;
if (head == null)
{
return null;
}
if (head.next == head)
{
return head;
}
while (Fast != null && Fast.next != null)
{
Fast = Fast.next.next;
Slow = Slow.next;
if (Fast == Slow)
{
break;
}
}
if (Fast == null || Fast.next == null)
{
return null;
}
if (Fast == Slow)
{
ListNode tmp = head;
while (true)
{
if (tmp == Slow)
{
break;
}
tmp = tmp.next;
Slow = Slow.next;
}
}
return Slow;
}
}
运行结果: