【leetcode】142. Linked List Cycle II

第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的代码部分是一样的,只是在返回的内容上有所区别

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值