142.环形链表II——学习笔记

发布时间 2023-03-25 22:28:59作者: 会飞的笨笨

题目:给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos-1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。

不允许修改链表。

示例 1
img

输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。

示例 2
img

输入:head = [1,2], pos = 0
输出:返回索引为 0 的链表节点
解释:链表中有一个环,其尾部连接到第一个节点。

示例 3
img

输入:head = [1], pos = -1
输出:返回 null
解释:链表中没有环。

提示

  • 链表中节点的数目范围在范围 [0, 104] 内
  • -105 <= Node.val <= 105
  • pos 的值为 -1 或者链表中的一个有效索引

题目来源:力扣(LeetCode)链接

题解

  • 自己做的(利用了Map)
    /**
    * 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) {
            if (head == null) { //如果链表为空,就直接返回null
                return null;
            }
            //创建map集合用来存放链表中的节点
            Map<ListNode,ListNode> nodeMap = new HashMap<>();
            ListNode temp = head;
            while (temp.next != null) {
                //先判断map集合中是否有当前节点的下一节点
                //如果有,那么当前节点的下一节点即是环形链表的起始节点
                if (nodeMap.containsKey(temp.next)) {
                    return temp.next;
                }
                //先判断再把节点放入map中
                nodeMap.put(temp, temp.next);
                temp = temp.next;//节点后移
            }
            //while循环结束,说明没有找到
            return null;
        }
    }
    
  • 快慢指针法(具体分析见代码随想录)
    img
    /**
    * 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 slow = head; //慢指针,每次走一步
            ListNode fast = head; //快指针,每次走二步
            //因为快指针每次走两步,所以需要判断fast和fast.next是否为空
            while (fast != null && fast.next != null) {
                slow = slow.next;//慢指针走一步
                fast = fast.next.next;//快指针走两步
                if (slow == fast) {//快慢指针相遇,说明有环
                    ListNode index1 = fast;//index1从相遇点开始出发
                    ListNode index2 = head;//index2从链表起始位置开始出发
                    //两者相遇时即为环形链表的起始位置
                    while (index1 != index2) {
                        index1 = index1.next;
                        index2 = index2.next;
                    }
                    //返回这个起始位置
                    return index1;
                }
            }
            //如果链表为空,或者没有环形链表,都会返回null
            return null;
        }
    }