LeedCode_141:给定一个链表,判断链表中是否有环

https://leetcode-cn.com/problems/linked-list-cycle/

在这里插入图片描述
使用快慢指针:操场上一个跑的慢和一个跑的慢的,两个人终究会相遇

/**
 * 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(fast!=null && fast.next!=null){
            if(slow==fast){
                return true;
            }
            //慢指针走一步
            slow = slow.next;
            //快指针走两步
            fast = fast.next.next;
        }
        return false;
    }
}
发布了665 篇原创文章 · 获赞 115 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/qq_42764468/article/details/104931489