LeetCode:M-142. Linked List Cycle II

30 篇文章 0 订阅
6 篇文章 0 订阅

LeetCode链接


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?


1、快慢指针,如果快指针追上慢指针,则表示有环

1)快慢指针起始都是head

2)快指针每次走2步,慢指针每次走1步

3)经过k步,快指针追上慢指针

2、查找环的开始点

1)设head到环的开始位置的步长为s

2)设环的开始位置到快慢指针相遇点,经过步长m,则 k=s+m -> s=k-m

3)设环的长为r步长,则快慢相遇时 k+nr=2k -> k=nr

4)由2),s = k-m = nr - m = (n-1)r + (r-m),r-m为快慢相遇点到环起点的距离

5)从head和快慢相遇点同时开始遍历,head会走s步, 快慢相遇点会走 (n-1)r + (r-m)步,由于(n-1)r就是绕环,不影响两者的相遇,遍历的相遇点就是环的开始点


TC = O(n)

/**
 * 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) {
	        if(head==null) return null;
	        
	        ListNode slow=head;
	        ListNode fast=head;
            boolean hasCycle=false;
	        while(fast.next!=null && fast.next.next!=null){
	            slow=slow.next;
	            fast=fast.next.next;
                if(slow==fast){
                    hasCycle=true;
                    break;
                }                    
	        }
	        	            
	        if(hasCycle){
	            slow = head;
	            while(slow != fast){
	                slow=slow.next;
	                fast=fast.next;
	            }
	            return slow;
	        }
	        return null;
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值