【LeetCode】141. Linked List Cycle(Java)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Rabbit_Judy/article/details/87993438

题目描述:给定一个链表,确定其中是否有一个循环。

为了表示给定链表中的循环,我们使用一个整数pos,它表示tail连接到的链表中的位置(0-index)。如果pos为-1,则链表中没有循环。

Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
在这里插入图片描述

/**
 * 判断链表是否有环
 *
 * @author wangfei
 */
public class Solution {
    /**
     * 利用快慢指针判断是否有环
     *
     * @param head
     * @return
     */
    public static boolean hasCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast)
                return true;
        }
        return false;
    }

猜你喜欢

转载自blog.csdn.net/Rabbit_Judy/article/details/87993438
今日推荐