查找链表中是否有环linked-list-cycle

时间:2023-03-10 07:55:39
查找链表中是否有环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?

不使用额外空间:这里没有实例化一个对象,只是引用对象,所以不会开辟新内存空间

用一个快指针和一个慢指针,当两个指针相遇,说明有环

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