第142是第141的一个升级版,
Given a linked list, determine if it has a cycle in it.
141要求的是查出是否存在有一个链表的循环;
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
142则是要求吧链表的第一个节点返回
public class Solution {
public ListNode detectCycle(ListNode head) {
Set<ListNode> nodes=new HashSet<>();
while(head!=null){
if(nodes.contains(head)){
return head;
}
else{
nodes.add(head);
head=head.next;
}
}
return null;
}
}
其实142和141的处理方法基本一致,只是返回的内容并不一样。
因为返回时,如果形成循环,根据每一步进行的head=head.next以及判断nodes.contains(head),其实现在已经通过链接回到了链表循环开始的地方。所以,此时只要返回head即可。
所以,本质上141和142的代码部分是一样的,只是在返回的内容上有所区别