141.环形链表

题目

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

分析

  • 判断链表有没有环的一个基本做法是用快慢指针,当快指针和慢指针重合的时候,说明有环,否则没有环。
  • 快指针每次走两步,慢指针每次走一步,只要有环一定能重合。就像沿着环形操场跑步,跑的快的一定能超过跑得慢的。

代码和注释

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    struct ListNode ret, *p, *q; //定义虚拟头节点和两个指针
    ret.next = head; //虚拟头节点指向真正的头节点
    p = q = &ret; //两个指针初始都指向虚拟头节点
    do {
        p = p->next;//由于p,q初始指向ret,一定不为null,所以有next属性 
        q = q->next;//慢指针p走一步,快指针q走两步
        if (q) { //如果q为null,不能执行下一步,并且直接跳出while循环,return fasle 
            q = q->next;
        }
    }while(p != q && q); //当p == q且q不为空的时候,可以判断有环
    if (q) return true;
    return false;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值