Linux commands

Tuesday, August 21, 2012

delete nth element linked list

void delete(int n)
{
        struct node *ptr=head;
        struct node *pre;
        int i=1;
        if((ptr != NULL) && n == 1)
        {
                head = head->next;
                free(ptr);
                return;
        }
        while(ptr != NULL)
        {
                if(i == n)
                {
                        pre->next = ptr->next;
                        free(ptr);
                        ptr=pre->next;
                        break;
                }
                pre= ptr;
                ptr= ptr->next;
                i++;
        }
}

No comments:

Post a Comment