您的位置:首页 > 职场人生

Linked List Cycle II

2016-03-14 21:41 531 查看
问题描述:

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?
代码实现:
/**
* 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 fast=head;
ListNode slow=head;
do{
if(fast!=null) fast=fast.next;
if(fast!=null){
fast=fast.next;
}else{
return null;
}
slow=slow.next;
}while(fast != slow);

slow=head;
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}

return slow;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 笔试 面试