简体   繁体   中英

Deleting occurrences of substring in string in singly linked list C

I have a little problem out here.

I must to program a singly linked list stuff, and I hadn't got any problems since now. I stuck on the deletion by the occurrence of the substring given after the function call in authors name in linked list.

the program snippet:

void list_delete_element(kniha_t* inode)
{
    kniha_t *actualnode = inode;
    kniha_t *prevnode = NULL;
    kniha_t *tempnode = NULL;

    uchar_t needle[100];
    uchar_t haystack[100];
    ushort_t occur = 0;

    scanf("%s", &needle);
    lower_string(needle);
    while(actualnode != NULL)
    {
        copy_string(haystack, actualnode->autori);
        lower_string(haystack);
        if(search_string(haystack, needle))
        {
            occur++;
            if ( NULL != prevnode)
            {
                prevnode->next = actualnode->next;
            }
            else
            {
                inode = actualnode->next;
            }
            tempnode = actualnode;
            actualnode = actualnode->next;
            free(tempnode);
            tempnode = NULL;
        }
        else
        {
            prevnode = actualnode;
            actualnode = actualnode->next;
        }
    }
    printf("Deleted sa %hu nodes\n", occur);
}


and the stuff I must load in it, ignoring the ---:
http://pastebin.com/NPvEr3y6

the problem is, that works ( :D )...until I sweep all the occurrences.

Example:
When I type in pra, it must delete all the nodes that contains "pra". It works like a charm...but when I type only "p", it tells me, that all the X occurrences were freed, but they stay in the buffer somewhere, because I can print the whole list out again!


I will be very thankful, who can give me some advice.

this statement:

 tempnode = NULL;

does nothing, actually, since you never do anything with tempnode besides assignment and immediately freeing.

Your list_delete_element should take kniha_t** so that you can delete the head node and prune linked list. With current code, you delete the node, but other functions doesn't know that because inode is not changed.

You you can update your code as

void list_delete_element(kniha_t* *inode)
{
    kniha_t *actualnode = *inode;
    ...
        if ( NULL != prevnode)
        {
            prevnode->next = actualnode->next;
        }
        else
        {
            *inode = actualnode->next;
        }
    ...
}

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