141. 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?

一刷
题解:
方法1, 用hashMap保存节点是否被visited的信息。如果新的节点已经存在了hashmap中,则有环。
方法2, 快慢指针,快指针每次前进两步,慢指针每次前进一步。如果慢指针和快指针重逢,说明有环。

/**
 * 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 || head.next == null)   return false;
        ListNode slow = head;
        ListNode fast = head.next;
       while(fast!=null && fast.next!=null){
           if(fast == slow) return true;
           fast = fast.next.next;
           slow = slow.next;
       }
        return false;
    }
}

二刷
快慢指针

/**
 * 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 || head.next==null) return false;
        ListNode slow = head, fast = head.next;
        while(fast!=null && fast.next!=null){
            if(fast == slow) return true;
            fast = fast.next.next;
            slow = slow.next;
        }
        return false;
    }
}

你可能感兴趣的:(141. Linked List Cycle)