141. 环形链表

38 篇文章 0 订阅
25 篇文章 0 订阅

在这里插入图片描述
要记住这样的写法,如果head为空或者单结点,直接false。如果不是就把慢指针设为head,快指针设为head->next,防止一开始直接相等。while结束的条件就是他俩相等,内部先判断快指针是否为null或者快指针的下一个是否为null,这很重要,很容易出错,这里只要判断快的,因为五环的话快的一定先走完。最后返回true

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        //链表=空间鲁棒性
        if(head == NULL || head->next == NULL) return false;
        //这两个赋初值必须这样来,不然直接进不去循环了
        ListNode* slow = head;
        ListNode* fast = head->next;
        while(slow != fast){
            //如果无环,也一定是fast先走到null
            //循环结束的条件就是slow=fast
            if(fast == NULL || fast->next == NULL) return false;
            slow = slow->next;
            fast = fast->next->next;
        }
        return true;
    }
};
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        //链表=快慢指针+空间鲁棒性
        //如果head为空或者head下一个为空就是false
        if(head == NULL || head->next == NULL) return false;
        ListNode* fast = head->next;
        ListNode* slow = head;
        //如果等于就退出循环并返回true,如果在途中fast走到null了就返回false
        while(fast != slow){
            if(fast == NULL || fast->next == NULL) return false;
            fast = fast->next->next;
            slow = slow->next;
        }
        return true;
    }
};
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool 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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值