目录java
给定一个链表,判断链表中是否有环。测试
为了表示给定链表中的环,咱们使用整数 pos 来表示链表尾链接到链表中的位置(索引从 0 开始)。 若是 pos 是 -1,则在该链表中没有环。3d
试题连接:https://leetcode-cn.com/problems/linked-list-cycle/指针
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
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
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; }
测试结果:索引
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
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