Loading

LeetCode problem#141

Linked List Cycle

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

27 lines
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 */
12public class Solution {
13    public boolean hasCycle(ListNode head) {
14        ListNode slow = head;
15        ListNode fast = head;
16
17        while (fast != null && fast.next != null) {
18            fast = fast.next.next;
19            if (fast == slow) {
20                return true;
21            }
22            slow = slow.next;
23        }
24
25        return false;
26    }
27}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.