Sunday, February 9, 2014

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?

Solution:
1. use hash map: O(N) time and O(N) space.(code blow)
2. use slow-fast approach. slow = slow.next while fast = fast.next.next. If there is a cycle, slow and fast would meet.


/**
 * 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) {
        HashMap hash = new HashMap();
        while(head != null){
            if(!hash.containsKey(head)){
                hash.put(head, true);
            }
            else if(hash.get(head)){
                return true;
            }
            head = head.next;
        }
        return false;
    }
}

No comments:

Post a Comment