Linked List Cycle

链表环检测方法
本文介绍了两种检测链表中是否存在环的方法:一是使用哈希映射记录已访问节点;二是采用双指针技术,其中一个指针移动速度为另一个的两倍,以此来判断链表是否有环。

Given a linked list, determine if it has a cycle in it.

 

判断某个链表是否有环。

方法一:

用一个hashmap来存放访问过的节点,通过比较当前节点是否存在map中来判断是否有环:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        Map<ListNode,Integer> map = new HashMap<ListNode,Integer>();
        while(head!=null) {
            if(!map.containsKey(head)) {
                map.put(head,1);
                head = head.next;
            }
            else return true;
        }
        return false;
    }
}

 

方法二:

用2个指针,慢指针一次后移一步,快指针一次后移2步,若有环则快指针会与慢指针相遇:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        try {
            while(fast!=null&&slow!=null) {
                fast = fast.next.next;
                slow = slow.next;
                if(fast==slow) return true;
            }
        }catch(Exception e){
            return false;
        }
        return false;
    }
}

 

转载于:https://www.cnblogs.com/mrpod2g/p/4345357.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值