踏踏实实积累,不要浮躁!!!
LeetCode https://leetcode-cn.com/problems/linked-list-cycle/submissions/
思路:判断链表是否有环,比较简单 直接利用快慢指针就能解决。
慢指针,一次走一步 快指针一次走两步 如果存在环则一定会相遇
/**
* 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){
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while(slow.next != null && fast.next != null && fast.next.next != null){
if(fast == slow){
return true;
}
slow = slow.next;
fast = fast.next.next;
}
return false;
}
}