哈希表和快慢指针解决142环形链表

哈希表

解题思路

  • 定义一个node结点指向头结点
  • 定义一个哈希表
  • 以node不为空为条件循环链表
  • 如果node结点已经存在于哈希表中,说明链表有环并且返回该node结点在链表中的位置
  • 否则node并不存在于哈希表中,将node添加到哈希表,node往后移动一个结点
  • 若循环执行结束,说明链表中不存在环,返回null
/**
 * 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 node = head;
        HashSet<ListNode> set = new HashSet<ListNode>();
        while(node != null){
            if(set.contains(node)){
                return node;
            }
            set.add(node);
            node = node.next;
        }
        return null;
    }
}

快慢指针

解题思路

  • 若头结点为空或者头结点下一节点为空,则链表无环返回null
  • 分别定义一个快指针和一个慢指针,都指向头结点
  • 以fast不为空作为条件循环遍历链表
  • 若快指针为空或者快指针下一节点为空,则链表无环返回null
  • 慢指针往后移动一个节点,快指针往后移动两个节点
  • 如果此时快慢指针相等,也就是链表有环;定义一个指向头结点的新结点node,以node结点和慢指针不相等为条件执行循环体,node结点和慢指针每次移动一个结点,当循环结束时,说明node和慢指针相遇,并且它们走过的距离恰好是链表环的第一个结点,返回node结点
  • 外层while循环顺利执行结束,说明链表不存在环,返回null

在这里插入图片描述

在这里插入图片描述

/**
 * 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 || head.next == null) return null;
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null){
            if(fast == null || fast.next == null){
                return null;
            }
            slow = slow.next;
            fast = fast.next.next;
            if(fast == slow){
                ListNode node = head;
                while(node != slow){
                    node = node.next;
                    slow = slow.next;
                }
                return node;
            }
        }
        return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值