题解 | #判断链表中是否有环#

判断链表中是否有环

https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9

import java.util.*;
/**
 * 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) {
        /*
        HashSet<ListNode> set = new HashSet<>();
        ListNode cur=head;
        while(cur!=null)
        {
            if(set.contains(cur)) return true;
            else{
                set.add(cur);
            }
            cur=cur.next;
        }
        return false;
        *///
	  
	  //双指针版本:如果一个链表有环,那么这个环一定是从尾部发出的
	  //slow指针每次走一步,fast指针每次走两步,如果有环二者一定会相遇
        ListNode fast=head;
        ListNode slow=head;
        while(fast!=null && slow!=null)
        {
            slow=slow.next;
            if(fast.next!=null)
                fast=fast.next.next;
            else return false;
            if(slow==fast) return true;
        }
        return false; 
    }
}

全部评论

相关推荐

大专境巅峰电子狗:头一次看到这种简历,学术与技术学习,直接用技能概括就好了呀,实习经历要写丰富一点
点赞 评论 收藏
分享
10-17 13:54
上海大学 运营
雾凇岛:这还说什么了,冲了兄弟们
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务