141. 环形链表(C语言)简单题

本文探讨了两种检测链表中是否存在环的有效算法:哈希方法和快慢指针。哈希方法通过创建一个哈希表来跟踪已访问的节点,而快慢指针则利用速度不同的两个指针来判断是否存在环。文章详细解释了两种方法的实现细节,并对比了它们的优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、哈希方法

哈希方法,哈希计算写得一般,没有找到合适的哈希值计算方法。非常浪费空间。

bool hasCycle(struct ListNode *head) {
    if(head==NULL)return false;
    struct ListNode *p=head;
    struct ListNode *q=head->next;
    long start=(long)head;
    int hashtable[1024*16]={0};
    while(p){
        hashtable[((long)p-start)/32]++;
        //printf("p address is (%x) (%d) \n",p,((long)p-start)/32);
        if(hashtable[((long)p-start)/32]>1)return true;
        p=p->next;
    }
    return false;
}

142 环形链表 II 

struct ListNode *detectCycle(struct ListNode *head) {

    if(head==NULL)return NULL;
    struct ListNode *p=head;
    struct ListNode *q=head->next;
    long start=(long)head;
    int hashtable[1024*16]={0};
    while(p){
        hashtable[((long)p-start)/32]++;
        //printf("p address is (%x) (%d) \n",p,((long)p-start)/32);
        if(hashtable[((long)p-start)/32]>1)return p;
        p=p->next;
    }
    return NULL;
}

 

二、快慢指针 

1.  p!=q

2. *q!=*p

对于while(p!=q)这一句,开始有些迷惑,错误的写成*q!=*p。

p!=q形式已经是在比较p和q变量里存储的内容,也就是节点的地址,不需要加*。加*,也就是*q!=*p形式,是取了节点的内容,也就是val或者*next。

如:

    int* a, * b;
    int x = 5, y = 6;
    a = &x; b = &y;
    if (a != b)printf("%d  %d  %d  %d  ", a, b, *a, *b);

bool hasCycle(struct ListNode *head) {
    if(head==NULL)return false;
    struct ListNode *p=head;
    struct ListNode *q=head->next;
    while(p!=q){
        if(q==NULL||q->next==NULL)return false;
        p=p->next;
        q=q->next->next;
    }
    return true;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值