链表算法之【获取链表开始入环的节点】
目录
LeetCode-142题
LeetCode-142题
给定一个链表的头节点head,返回链表开始入环的第一个节点,如果链表无环,则返回null
class Solution {public ListNode detectCycle(ListNode head) {// checkif (head == null || head.next == null)return null;// 链表是否有环的标识,初始值设置为falseboolean hasCycle = false;// 定义两个指针,一个快指针[fast],一个慢指针[slow],并且它们开始都指向头节点ListNode fast = head;ListNode slow = head;// fast指针一次前进两个节点,slow指针一次前进一个节点while (fast != null && fast.next != null) {fast = fast.next.next;slow = slow.next;// 如果fast和slow能相遇,链表存在环if (fast == slow) {hasCycle = true;break;}}// 链表无环,返回nullif (!hasCycle) {return null;}// fast指针回到初始位置,也就是头节点// 快慢指针都每次前进1个节点,再次相遇的位置就是第一次开始入环的节点位置fast = head;for (; ; ) {// 有可能在回到头节点就相遇if (slow == fast)return slow;slow = slow.next;fast = fast.next;if (slow == fast)return slow;}}private static class ListNode {int val;ListNode next;public ListNode() {}public ListNode(int val) {this.val = val;}public ListNode(int val, ListNode next) {this.val = val;this.next = next;}}
}