您的位置:首页 > 其它

开始刷leetcode day12:Linked List Cycle II

2015-05-14 12:34 393 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return
null
.

Follow up:

Can you solve it without using extra space?

Java:

/**

* 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 || head.next == null) return null;

ListNode l1 = head;

ListNode l3 = head;

do{

if(l3.next!=null && l3.next.next != null)

{

l3 = l3.next.next;

l1 = l1.next;

}else return null;

}while( l1!=l3);

ListNode l4 = head;

while(l4 != l1)

{

l4 = l4.next;

l1 = l1.next;

}

return l1;

}

}

思路 :现弄两个pointer,一个用1的速度走,一个用2的速度走。遇到的时候l1走了n,l3走了2n。假设head到循环入口有k步,那么l1在相遇的时候走进了cycle里n-k步。剩下再走k部就可以到cycle的入口处。

这时在弄一个pointer l4从head走,当l4遇到l1时,正好走k步时相遇在cycle的入口。返回之即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: