Home > other >  Trying to delete node from a particular position . But I can only delete when in only input position
Trying to delete node from a particular position . But I can only delete when in only input position

Time:05-17

after running the code ,the program ask the position from where you want to delete a node . I ran the code but it only work when I input postion 1 .For other position like 2,3,4 it does not work .

here i want to insert number at end of a node :

void Insert(int data)
{
    struct node* temp1;
    temp1=(struct node*)malloc(sizeof(struct node));
    temp1->data=data;
    temp1->next=NULL;

    if (head==NULL){
        temp1->next=head;
        head=temp1;
    }
    else{
        struct node* temp2;
        temp2=head;
        while(temp2->next!=NULL)
        {
            temp2=temp2->next;
        }

        temp2->next=temp1;
    }
}

Print function:

void Print()
{
    struct node*temp99;
    temp99=head;
    while(temp99!=NULL){
        printf(" %d",temp99->data);
        temp99=temp99->next;
    }
    printf("\n");
}

Delete function:

void Delete(int n)
{
    struct node* temp33;
    temp33=head;

    if (n==1)
    {
        head=temp33->next;
        free(temp33);
    }
    else{
        int i;
        for (i=0;i<n-2;i  )
        {
            temp33=temp33->next;
        }
        struct node* temp44;
        temp44=temp33->next;

        temp44->next=temp33->next;

        free(temp44);
    }
}

CodePudding user response:

Replace temp44->next=temp33->next; with temp33->next=temp44->next;.

And give better names to your variables.

CodePudding user response:

For starters indices shall start from 0. Secondly the function parameter shall have an unsigned integer type as for example size_t.

When n is not equal to 1 these manipulations with pointers

    struct node* temp44;
    temp44=temp33->next;

    temp44->next=temp33->next;

    free(temp44);

do not make a sense. For example data member next of the pointer temp33 is not changed.

And moreover this for loop

    for (i=0;i<n-2;i  )
    {
        temp33=temp33->next;
    }

can invoke undefined behavior because there is no check whether temp33 is not equal to NULL.

Even this code snippet

if (n==1)
{
    head=temp33->next;
    free(temp33);
}

can invoke undefined behavior when the list is empty that is when head is equal to NULL.

The function can be defined the following way

int Delete( size_t n ) 
{
    struct node **current = &head;

    while ( *current != NULL && n )
    {
        current = &( *current )->next;
        --n;
    }

    int success = *current != NULL;

    if ( success )
    {
        struct node *node_to_delete = *current;
        *current = ( *current )->next;
        free( node_to_delete );
    }

    return success;
}
  • Related