141. Linked List Cycle (amazon)

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

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

 

Solution: solve the problem with one and two steps

no cycle case: the faster pointer(two step) reaches the null first

cycle : slower == faster 

Caution: check the null case

/**
 * 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;
        if(head.next == null) return false;
        //with extra space
        //a -> b ->c -> d -> a;
        ListNode  one = head;
        ListNode  two = head;
        while(two.next != null && two.next.next !=null){
            one = one.next;
            two = two.next.next;
            if(one==two) return true;
        }
        return false;
    }
}

 

posted @ 2018-05-25 09:43  wz30  阅读(85)  评论(0编辑  收藏  举报