[面试经典编程题] 1 判断链表有环与否

题目:判断链表是否有环

题目描述

image-20200713203447257

示例

image-20200713203509333

image-20200713203520011

进阶:

你能用 O(1)(即,常量)内存解决此问题吗?

Java代码

方法1:快慢指针

/**
 * 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) {
        //判断只有一个节点的情况
        if(head==null || head.next==null){return false;}

        //不是一个节点或者为空的时候,就执行快慢指针
        ListNode slow = head;
        ListNode quick = head.next;

        //if(head.next==head) {return true;}
        while(slow != quick){
            if(quick==null || quick.next==null) {return false;}
            slow = slow.next;
            quick = quick.next.next;
        }
        //退出while循环,即有环
        return true;
        
    }
}

方法2:哈希表

//方法2 哈希表
    public boolean hasCycle(ListNode head) {
        //判断只有一个节点回或者无头节点的话即无环
        if(head==null || head.next==null) {return false;}
        //哈希表
        Set<ListNode> set = new HashSet<ListNode>();
        while(head!=null){
            if(set.contains(head)){
                return true;
            }else{
                set.add(head);
            }
            head = head.next;
        }
        return false;
    }
}
原文地址:https://www.cnblogs.com/jiyongjia/p/13295573.html