Josh
Josh

Reputation: 113

Popping an empty linked list in C

So my goal is to remove a linked list head node. But I am having trouble doing that when I have an empty list here is what I have so far

conscell *ll_pop(conscell *list)
{
    if ( list == NULL) {            // do nothing
        return list;
    }
    if ( list != NULL) {
        conscell *p = list->next;
        free(list);
        list = p;
        return list;
    }

Here is the implementation. We do a series of pops. First we pop two nodes then we pop 3 nodes

 conscell *ll_push(conscell *list, void *data)
{
    conscell *new = xmalloc(sizeof *new);   // allocate associate memory
    new->data = data;           // assign data
    new->next = list;           // attach the new node to the old list
    return new;
}

Upvotes: 0

Views: 253

Answers (2)

Rishikesh Raje
Rishikesh Raje

Reputation: 8614

What you need to do is to use the return value of the pop to modify the list pointer.

Your main should look something like this.

int main(void)
{
    conscell *list= NULL;

    ....

    list = ll_push(list,data1);
    list = ll_push(list,data2);
    list = ll_push(list,data3);
    list = ll_push(list,data4);

    list = ll_pop(list);
    list = ll_pop(list);        
    list = ll_pop(list);
    list = ll_pop(list);
    list = ll_pop(list);

}

The 4th pop will assign the list pointer back to NULL and the fifth and further pops will just return normally.

Upvotes: 0

MortalMan
MortalMan

Reputation: 2612

How are you defining an empty list? Set the list to NULL in main before calling the function, and it should work.

Upvotes: 2

Related Questions