Monday, March 19, 2018

[2018-Interview] Linked List Cycle

Original question: https://leetcode.com/problems/linked-list-cycle/description/

My answer: have 2 nodes running in the list, one fast, one slow. If there is a cycle, they will meet somewhere. If not, the fast will reach end of the list first.


/**
 * 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) {
            return false;
        }
        ListNode p1 = head;
        ListNode p2 = head.next;

        while(p2 != null && p2.next != null && p1 != p2) {
            p1 = p1.next;
            p2 = p2.next.next;
        }

        if (p2 == p1) {
            return true;
        }
        return false;
    }
}

No comments:

Post a Comment