Advertisement
korobushk

cycle2

May 3rd, 2021
1,367
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.56 KB | None | 0 0
  1. public class Solution {
  2.     public ListNode detectCycle(ListNode head) {
  3.         ListNode p1 = head;
  4.         ListNode p2 = head;
  5.        
  6.        
  7.         while(p2!=null&&p2.next!=null){
  8.             p1=p1.next;
  9.             p2=p2.next.next;
  10.             if(p1==p2){
  11.               break;
  12.             }
  13.         }
  14.         if (p2 == null || p2.next == null){
  15.         return null;
  16.     }
  17.        
  18.         ListNode p3 = head;
  19.         while(p3!= p2){
  20.             p3=p3.next;
  21.             p2=p2.next;
  22.            
  23.         }
  24.        
  25.         return p3;
  26.        
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement