链表是否存在环,有则返回入环结点

public static Node entryNode(Node head){
		if(head==null)return null;
		Node p=isloop(head);	//环中某一节点
		Node q=p.next;			//计算环中结点个数
		int count=1;			//环的结点总数量count
		while(q!=p){			
			q=q.next;
			count++;
		}
		//找到环入口
		p=head;		//快指针		   
		q=head;		//慢指针
		for(int i=0;i<count;i++){//第一个结点先走count步
			p=p.next;
		}
		while(p!=q){		//快慢一起走,相等则为入口
			p=p.next;
			q=q.next;
		}
		return p;
		
	}
	public static Node isloop(Node head){//链表是否有环
		Node first=head.next;//first在second后面原因:防止在环之前两者相等
		Node second=head;
		while(first.next!=null&&first.next.next!=null){
			if(first==second){
				return first;
			}
			first=first.next.next;
			second=second.next;
		}
		return null;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值