思路
链表判环方法:快慢指针法
其实没那么高级,很简单的理解就是,采用两个指针,一个每次走两步,一个每次走一步,如果链表有环,那么每次走两步的指针,也就是走得快的指针一定会追上走得慢指针。
代码
第一种写法:
// 写法1
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) return false;
ListNode slow = head, fast = head.next;
while(slow != fast){
if(fast == null || fast.next == null){
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}
第二种写法:
// 写法2
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) return false;
ListNode slow = head, fast = head;
while(true){
if(fast == null || fast.next == null){
break;
}
slow = slow.next;
fast = fast.next.next;
if(slow == fast) return true;
}
return false;
}
}
标签:Leetcode141,head,slow,return,环形,fast,next,链表,null
From: https://blog.csdn.net/qq_73179413/article/details/143836379