题目:
给定一个链表,如果它是有环链表,实现一个算法返回环路的开头节点?。若环不存在,请返回null。
如果链表中有某个节点,可以通过连续跟踪next?指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数pos?来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果pos?是-1?,则在该链表中没有环。注意:?pos不作为参数进行传递,仅仅是为了标识链表的实际情况。
示例 1:
输入:head = [3,2,0,-4], pos = 1输出:tail connects to node index 1解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0输出:tail connects to node index 0解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1输出:no cycle解释:链表中没有环。
代码实现:
public class Solution { public ListNode detectCycle(ListNode head) { if (head == null) { return null; } ListNode slow = head, fast = head; while (fast != null) { slow = slow.next; if (fast.next != null) { fast = fast.next.next; } else { return null; } if (fast == slow) { ListNode ptr = head; while (ptr != slow) { ptr = ptr.next; slow = slow.next; } return ptr; } } return null; }}
【文章原创作者:建湖网页开发公司 jianhu.html 欢迎留下您的宝贵建议】可是旅行的彼时那刻我的心情一直是好的吗?