leetcode--Linked List Cycle

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

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

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 boolean hasCycle(ListNode head) {  
  14.         if(head==nullreturn false;          
  15.         ListNode slow = head.next;  
  16.         ListNode fast = null;  
  17.         if(slow==nullreturn false;  
  18.         else fast = slow.next;  
  19.           
  20.         while(slow!=null&&fast!=null){  
  21.             if(slow==fast) return true;  
  22.             else{  
  23.                 slow = slow.next;  
  24.                 if(fast.next!=null) fast = fast.next.next;  
  25.                 else return false;  
  26.             }  
  27.         }  
  28.         return false;  
  29.     }  

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