Linked List Cycle

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

Follow up:
Can you solve it without using extra space?

Thinking: Using fast & slow runner method. If one leap forward two steps per time, and one leap forward one step per time. If there is a cycle, then the fast runner will catch the slow one at some point.

 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || == null) return false;
        ListNode fast =;
        ListNode slow = head;
        while (fast != null && != null) {
            if (fast == slow) return true;
            fast =;
            slow =;
        return false;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s