简体   繁体   中英

C linked list and pointers

Can somebody please explain what this code with pointers does:

    while(terminate== 0)
    {
        s->value=s->next->value; 
        if ((s->next->next)==NULL)
        {
            free(s->next); 
            s->next=NULL;
            terminate= 1;
        }
        s=s->next;
    }

where s is passed as a parameter as : set_el* s and having this structure below:

 typedef struct set_el
 {
   int value;
    struct set_el* next;
 } set_el;

In case of NULL input it will cause a segmentation fault since s->value is illegal.

On a list of size 1 it will similarly fail because s->next->value is illegal.

On a list with a loop (for instance a>b>a...) it will loop endlessly because s->next->next will never be NULL

Finally on a linked list of size 2 or above it will traverse the list coping the value of the next node to the current node and delete the last node.

Effectively it will 'remove' the first node in the list in a very roundabout way. (We free up the last node memory but we copy the values up the list. The new list is 1 node shorter and without the value in the first node).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM