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

判断链表中是否有环

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

NC4 判断链表中是否有环

我的第一种解题思路,双指针迭代(快慢指针)。两个指针向后移动的速度不一样,如果快指针没有到null,而是两个指针指向了同一个节点的话,那么说明链表中就是有换存在的。

 public boolean hasCycle(ListNode head) {
        if(head==null||head.next==null){
            return false;
        }
        ListNode slow=head,fast=head.next;
        while(slow!=fast){
            if(fast==null||fast.next==null){
                return false;
            }
            slow=slow.next;
            fast=fast.next.next;
        }
        return true;
    }

第二种解题思路,利用Set存储元素不可重复的特性。但是这里需要自己导包。

import java.util.Set;
import java.util.HashSet;

 public boolean hasCycle(ListNode head) {
        if(head==null||head.next==null){
            return false;
        }
        Set<ListNode>set=new HashSet<ListNode>();
        while(head!=null){
            if(!set.add(head)){
                return true;
            }
            head=head.next;
        }
        return false;
    }
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务