相关标签
一、题目要求
二、题解和代码实现
1.题解
2.代码实现
代码如下(示例):
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode nodehead = head;//记录头
HashSet< ListNode> set = new HashSet<>();//创建hash表,存储节点
while (nodehead!=null){//遍历
if (set.contains(nodehead)){//查看是否在hash表中,如果在 说明有环,因为是存节点,所以地址信息也会被判断是否存在
return nodehead;//返回当前链表节点
}else {//说明不在hash表中
set.add(nodehead);//存节点到hash表中
}
nodehead =nodehead.next;//指针移动
}
return null;
}
}