[LeetCode] 141-Linked List Cycle

来源:互联网 发布:unity3d ugui 画线 编辑:程序博客网 时间:2024/06/01 20:43

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;    }}
原创粉丝点击