Deletion absolute value of the same node 2015

Thought: space for time, because | data | <= n, the assist array of length n + 1, the initial value of each element is 0, the list of each node sequentially scanned while checking q [| data |] If the value of 0, leave the node, the Bing value of 1, otherwise, remove the node.

Code:

void func(PNODE h,int n)
{
    PNODE p,h,r;
    int *q,m;
    q=(int *)malloc(sizeof(int)*n+1);
    for(int i=0;i<n+1;++i)
        *(q+i)=0;
    while(p->next!=NULL)
    {
        m=p->next->data>0?p->next->data:-p->next->data;
        if (* (q + m) == 0) // first time
        {
            *(q+m)=1;
            p=p->next;
            
        }
        else {// delete repeated
            r=p->next;
            p->next=r->next;
            free(r);
        }
    }
    free(q);
}

  Time O (1), a space O (n)

Guess you like

Origin www.cnblogs.com/yangmenda/p/11707568.html