Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers in c: Function which deletes every second element of linked list

I want to write a function which gets a pointer to a header of a linked list and deletes from the list every second member of it. The List is a linked elements of type element:

typedef struct element{
    int num;
    struct element* next;
}element;

I'm new to all these pointers arithmetic so I'm not sure I write it correctly:

 void deletdscnds(element* head) {
    element* curr;
    head=head->next; //Skipping the dummy head//

    while (head!=NULL) {
        if (head->next==NULL) 
            return;

            else {
                curr=head;
                head=head->next->next; //worst case I'll reach NULL and not a next of a null//
                curr->next=head;
            }
        }
    }

I kept changing it since I kept finding errors. Can you please point out any possible errors?

like image 981
Jozef Avatar asked Dec 27 '22 21:12

Jozef


1 Answers

The algorithm is a lot simpler if you think of your linked list in terms of node pairs. Each iteration of your loop should process two nodes - head and head->next, and leave head equal to head->next->next upon exit. It is also important to not forget deleting the middle node, if you are cutting it out of the list, otherwise you are going to see memory leaks.

while (head && head->next) {
    // Store a pointer to the item we're about to cut out
    element *tmp = head->next;
    // Skip the item we're cutting out
    head->next = head->next->next;
    // Prepare the head for the next iteration
    head = head->next;
    // Free the item that's no longer in the list
    free(tmp);
}
like image 106
Sergey Kalinichenko Avatar answered Apr 28 '23 18:04

Sergey Kalinichenko