[LeetCode] 141-Linked List Cycle

Question

Given a linked list, determine if it has a cycle in it.

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

Solution

1)Use two pointers, walker and runner.
2)walker moves step by step. runner moves two steps at time.
3)if the Linked List has a cycle walker and runner will meet at some point.

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(null == head){
            return false;
        }
        ListNode walker = head;
        ListNode runner = head;
        while(walker.next != null && runner.next != null && runner.next.next != null){
            walker = walker.next;
            runner = runner.next.next;
            if(walker == runner){
                return true;
            }
        }
        return false;
    }
}

Question

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?

Solution

1)two pointer, walker and runner, meet at the same node after k step。
此时:walker走了k步,runner走了2k步。runner比walker多绕了环n圈,假设环的长度为r。
可得 2k-k=nr , k=nr

2)walker走的距离可以分为两部分,总长度为k,从链表head到环的起点为s,环的起点到相交的点的距离为m。
可得 k=s+m

3)联立两式可得 s = nr - m

4)一个指针从链表head走S步,正好到达环的起点。
一个指针,从相交点,走S步,也正好到达环的起点。(相当于绕n圈,然后后退m步)

/**
 * 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(null == head || null == head.next){
            return null;
        }
        ListNode walker = head;
        ListNode runner = head;
        wihle(walker.next != null && runner.next != null && runner.next.next != null){
            walker = walker.next;
            runner = runner.next.next;
            if(walker == runner){
                //链表有环
                ListNode first = head;
                ListNode second = walker;
                while(first != second){
                    first = first.next;
                    second = second.next;
                }
                return first;
            }
        }
        return null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值