Home > Mobile >  How do I build a linked list function that can make changes to nodes and to the head pointer?
How do I build a linked list function that can make changes to nodes and to the head pointer?

Time:08-28

I have built a linked list in C where each node is a character. So my linked list represents a string. I am trying to create a function that removes a number of characters starting from a position. I wrote the following:

listNode *removeChars(listNode *wordList, int pos, int lnth) {
    listNode *curr = wordList;
    listNode *prev = NULL;

    for (int i = 0; i < pos-1; i  ) {
        prev = curr;
        curr = curr->next;        
    }
    for (int i = 0; i < lnth; i  )
       curr = curr->next;
    prev->next = curr;
    return wordList;
}

where lnth represents the number of characters to remove starting from pos. It works fine...EXCEPT when my pos == 1. To handle this exception, I wrote the following code:

void removeFirstChar(listNode **wordList, int lnth) {
    listNode *curr = *wordList;
    for (int i = 0; i < lnth; i  )
        curr = curr->next;
    *wordList = curr;
}

My question is:

How do I merge both functions so I end up with one function that can handle both cases, pos = 1 and pos > 1?

CodePudding user response:

I suppose that you should create new nodes in the list dynamically using function malloc.

It means that you need to free allocated nodes that must be removed from the list.

You do not check whether the pointer to the head node is equal to NULL. So in any case your function can invoke undefined behavior.

If a function can change an object as for example the pointer to the head node then you should pass the object to the function by reference.

In C passing by reference means passing an object indirectly through a pointer to it. Thus dereferencing the pointer within the function it can get a direct access to the original object and change it.

Your function can be declared and defined the following way

size_t removeChars( listNode **wordList, size_t pos, size_t n ) 
{
    size_t count = 0;

    while ( *wordList != NULL && pos )
    {
        --pos;
        wordList = &( *wordList )->next;
    }

    if ( pos == 0 )
    {
        while ( *wordList && n-- )
        {
            listNode *tmp = *wordList;
            *wordList = ( *wordList )->next;
            free( tmp );
              count;
        }
    }

    return count;
}

The function returns the actual number of removed nodes from the list.

As in C indices start from 0 then the value of the parameter pos also starts from 0.

  • Related