LeetCode - 141 Linked List Cycle

作者 QIFAN 日期 2016-07-15
LeetCode - 141 Linked List Cycle

Difficulty:Easy

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

思路

设置快慢指针,如果两个指针相遇则有环

注意空指针

代码

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

原题链接:https://leetcode.com/problems/linked-list-cycle/