leetcode--Linked List Cycle II

来源:互联网 发布:数据洪流 编辑:程序博客网 时间:2024/06/06 00:46

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] view plain copy
  1. /** 
  2.  * Definition for singly-linked list. 
  3.  * class ListNode { 
  4.  *     int val; 
  5.  *     ListNode next; 
  6.  *     ListNode(int x) { 
  7.  *         val = x; 
  8.  *         next = null; 
  9.  *     } 
  10.  * } 
  11.  */  
  12. public class Solution {  
  13.     public ListNode detectCycle(ListNode head) {  
  14.         if(null == head || null == head.next) return null;  
  15.         ListNode slow = head;  
  16.         ListNode fast = head;  
  17.         while(slow != null && fast != null && fast.next != null){  
  18.             slow = slow.next;  
  19.             fast = fast.next.next;  
  20.             if(slow == fast){  
  21.                 slow = head;  
  22.                 while(slow != fast){  
  23.                     slow = slow.next;  
  24.                     fast = fast.next;  
  25.                 }  
  26.                 return slow;  
  27.             }  
  28.         }  
  29.         return null;  
  30.     }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46563883

原创粉丝点击