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

一、哈希方法

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

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;
}

 

你可能感兴趣的:(力扣题目)