题目链接:LeeCode141环形链表
题目描述:
题拿到手首先想到了应该判断当前点是否来过,如果没来过,接着走,如果再次来到了来过的点,结束,但是这个来没来过在不改变链表节点的情况下不太好完美判断。但题也过了
public static boolean hasCycle(ListNode head) {
List<Integer> list=new ArrayList<>();
while(head!=null){
if(head.val==Integer.MIN_VALUE)return true;
head.val=Integer.MIN_VALUE;
head=head.next;
}
return false;
}
然后总感觉判定的不是太完美所以就找找题解,于是用快慢指针写了一个,思路也挺简单,但是我竟然没想到,开始设定两个指针一个设定在头节点,一个设定在头节点之后然后一个每次移动一步,一个每次移动两步,如果有循环的话两个指针会在某刻重合,如果没有循环永远不会重合
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}