一、题目
给定一个链表,如果它是有环链表,实现一个算法返回环路的开头节点。若环不存在,请返回 null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
二、解题思路
想要判断链表中是否存在环路,可以使用java中的HashSet集合,每遍历一个节点,就将其加入到HashSet中,如何HashSet中不存在该节点,则返回true,否则返回false。因此当再次遍历到重复节点时,HashSet会返回false,则说明存在重复节点。该集合经常用来判断是否存在重复节点。需要在做题中,熟练掌握该方法。
三、代码
/**
* 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) {
Set<ListNode> set=new HashSet<ListNode>();
ListNode pos=head;
while(pos!=null) {
if(!set.add(pos)) {
return pos;
}
pos=pos.next;
}
return null;
}
}