链表-Linked List Cycle II(判断一个链表是否有环)

问题描述:

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?

思考:

参考了网上的方法,判断一个单向链表是否有环,如果没有返回空,如果有返回这个环的开始处,也就是和前面直线的焦点。
 画出图: 从开始的节点分别放慢指针和快指针两个指针,快的每次走两步,慢的每次走一步。
类似时针分针,如果链表有环,两个指针一定会在环中相遇,此时即可推断:
2s = nc+s,
s=a+x,
=>  a+x=nc,
a=nc-x,
a=(n-1)c+c-x其中n-1为整数圈数,这个意思是当两个指针相遇的时候,把快指针放回头节点,慢指针在原处,快指针每次就只走一步了,此时快指针走到环开始的地方时,慢指针走了剩余的半圈加(n-1)个整圈,以此找出环开始处。

代码(java):

public class LinkedListCycleII {

	static class ListNode {
		int val;
		ListNode next;
		ListNode(int x) {
			val = x;
			next = null;
		}
	}

	public ListNode detectCycle(ListNode head) {

		 ListNode slow,fast;

			//只有一个节点或者就没有
			if(head == null || head.next == null){
				return null;
			}


			//正式开始
			slow = head;
			fast = head;
			
			while(true){
				
				if(fast == null || fast.next == null){
					return null;
				}
				
				slow = slow.next;
				fast = fast.next.next;
				if(slow == fast){
					break;
				}
			}
			
			slow = head;
			
			while(true){
				
				if(slow == fast){
					break;
				}	
				slow = slow.next;
				fast = fast.next;
			}
			
			return slow;
	}


}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值