剑指offer链表中的入口节点

题目描述

给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

题目分析

不同于判断链表是否有环,这道题是要找到环形链表入口节点。
题目中有环链表类似于下图:
在这里插入图片描述

方法一:哈希法

遍历单链表的每个结点
如果当前结点地址没有出现在set中,则存入set中
否则,出现在set中,则当前结点就是环的入口结点
整个单链表遍历完,若没出现在set中,则不存在环

判断是否有环。

public class Solution {
    public boolean hasCycle(ListNode head) {
        Set<ListNode> seen = new HashSet<ListNode>();
        while (head != null) {
            if (!seen.add(head)) {
                return true;
            }
            head = head.next;
        }
        return false;
    }
}

找出入口节点。

public class Solution {
    public ListNode hasCycle(ListNode head) {
        Set<ListNode> seen = new HashSet<ListNode>();
        //返回值不同。
        while (head != null) {
            if (!seen.add(head)) {
                return head;
            }
            head = head.next;
        }
        return null;
    }
}

双指针

判断是否有环

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        //两个节点初始化都要为head;
        ListNode slow = head;
        ListNode fast = head;
        while(fast!=null && fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                return true;
            }
        }
        return false;
    }
}

在这里插入图片描述

找出入口节点

以上图为例,相遇在C点,那么2(AB + BC) = AB + BC + CB + BC(简单考虑,等号左边是slow,右边是fast)。
所以AB = CB,找到相遇节点后令fast = head,然后每次都走一步,相交结点就是B点,也就是环的入口节点。这就是判断是否有环和找出环的入口节点的区别。当然,我们要使fast和slow都从head开始。

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        //两个节点初始化都要为head;,相交时才能够得出距离是相等的。
        ListNode slow = head;
        ListNode fast = head;
        while (fast!=null && fast.next!=null) {
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                break;
            }
        }
        //区别就在于,找到相交结点之后,再找出环的入口节点。
        if (fast==null || fast.next == null) return null;
        fast = head;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值