Advertisement
CreateWithChirag

Linked List Cycle Leetcode

Jan 15th, 2023
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.66 KB | Source Code | 0 0
  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.        //base case
  15.        if(head == null || head.next == null){
  16.            return false;
  17.        }
  18.  
  19.        ListNode slow = head;
  20.        ListNode fast = head;
  21.  
  22.        while(fast.next != null && fast.next.next != null){
  23.            slow = slow.next;
  24.            fast = fast.next.next;
  25.  
  26.            if(slow == fast){
  27.                return true;
  28.            }
  29.        }
  30.        return false;
  31.     }
  32. }
Tags: leetcode
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement