【leetcode】【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?

二、问题分析

典型的two points问题,通过设置快慢指针,如果有环,那么快指针总会追上慢指针;如果不存在环,那么快指针会先指向null。

三、Java AC代码

public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
			return false;
		}
		ListNode slow = head;
		ListNode fast = head;
		while (fast!=null && fast.next != null) {
			fast = fast.next.next;
			slow = slow.next;
			if (fast == slow) {
				return true;
			}
		}
		return false;
    }


你可能感兴趣的:(java,LeetCode,list)