【算法】Hash实现环形链表【LeetCode】

一、 题目:给定一个链表,判断链表中是否有环。

条件:如果链表中存在环,则返回 true 。 否则,返回 false 。

二、题解

  1. 链表结点
class ListNode {
    
    
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
    
    
 *         val = x;
 *         next = null;
 *     }
 * }

2.hash实现

public class Solution {
    
    
    public boolean hasCycle(ListNode head) {
    
    
    if(head==null||head.next==null){
    
    
		return false;
    }
    Set<ListNode> set=new LinkedHashSet();//哈希表用于保存链表结点的值
    while(head!=null){
    
    
        if(set.contains(head)){
    
    //如果访问到已经访问过的结点则说明链表有环
            return true;
        }
        set.add(head);//否则将结点的值放入哈希表,继续遍历
        head=head.next;//获得下一个结点
    }
    return false;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43073558/article/details/108841731