Advertisement
sweet1cris

Untitled

Jan 9th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.77 KB | None | 0 0
  1.  
  2. /**
  3.  * Definition for ListNode.
  4.  * public class ListNode {
  5.  *     int val;
  6.  *     ListNode next;
  7.  *     ListNode(int val) {
  8.  *         this.val = val;
  9.  *         this.next = null;
  10.  *     }
  11.  * }
  12.  */
  13. public class Solution {
  14.     public ListNode detectCycle(ListNode head) {
  15.         if (head == null || head.next==null) {
  16.             return null;
  17.         }
  18.  
  19.         ListNode fast, slow;
  20.         fast = head.next;
  21.         slow = head;
  22.         while (fast != slow) {
  23.             if(fast==null || fast.next==null)
  24.                 return null;
  25.             fast = fast.next.next;
  26.             slow = slow.next;
  27.         }
  28.        
  29.         while (head != slow.next) {
  30.             head = head.next;
  31.             slow = slow.next;
  32.         }
  33.         return head;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement