leetcode-141. 环形链表

141. 环形链表

一、题目描述

给定一个链表,判断链表中是否有环。测试

为了表示给定链表中的环,咱们使用整数 pos 来表示链表尾链接到链表中的位置(索引从 0 开始)。 若是 pos 是 -1,则在该链表中没有环。3d

试题连接:https://leetcode-cn.com/problems/linked-list-cycle/指针

二、先来介绍三种奇葩的作法

2.一、判定链表长度不超过10000

public static boolean hasCycle(ListNode head) {
        //定义末尾指针,指向尾部
        ListNode p2 = head;
        int size = 1;
        while (p2 != null) {
            p2 = p2.next;
            size++;
            if(size > 10_000) {
                return true;
            }
        }
        return false;
    }

测试结果:code

2.二、判定遍历时间不超过1ms

public static boolean hasCycle(ListNode head) {
        //定义末尾指针,指向尾部
        ListNode p2 = head;
        long start = System.currentTimeMillis();
        while (p2 != null) {
            p2 = p2.next;
            if(System.currentTimeMillis() - start > 1) {
                return true;
            }
        }
        return false;
    }

测试结果:blog

2.三、判定链表中没有-1000000000的数字

public static boolean hasCycle(ListNode head) {
        //定义末尾指针,指向尾部
        ListNode p2 = head;
        while (p2 != null) {
            if(p2.val == -1000000000) {
                return true;
            }
            p2.val = -1000000000;
            p2 = p2.next;
        }
        return false;
    }

测试结果:索引

三、快慢指针法

3.一、java语言实现

public static boolean hasCycle(ListNode head) {
        if(head == null || head.next == null)
            return false;

        //快慢指针法
        ListNode p1 = head;     //快指针
        ListNode p2 = head;     //慢指针

        while(p1 != null && p2 != null && p1.next != null) {
            p1 = p1.next;

            if(p1 == p2) {
                return true;
            }
            p2 = p2.next;
            p1 = p1.next;
        }
        return false;
    }

测试结果:leetcode

3.二、C语言实现

bool hasCycle(struct ListNode *head) {
    if(head == NULL || head->next == NULL)
        return false;

    //快慢指针法
    struct ListNode* p1 = head;     //快指针
    struct ListNode* p2 = head;     //慢指针

    while(p1 != NULL && p2 != NULL && p1->next != NULL) {
        p1 = p1->next;

        if(p1 == p2) {
            return true;
        }
        p2 = p2->next;
        p1 = p1->next;
    }
    return false;
}

测试结果:get

相关文章
相关标签/搜索