user3739406
user3739406

Reputation: 364

How to remove the last item in a linked list?

I'm working on a linked list program, and am trying to remove the last item. I've attempted the function down below, but it's faulty and leads to a seg fault.

I've got a struct as such in a header file:

struct test{
 char * name;
 char * type;
 struct test * next;
};

And I've got a function in a separate .c file, as such:

//NOTE Correct memory is allocated in other parts of the program
//(i.e not in this function)
//Also values are initialized in other functions...etc

test * removeLastItem(test * head)
{
    test * parent, * cursor;

    if(head == NULL) //if list is empty return NULL
    {
        return NULL;
    }

    else
    {
        while(cursor->next != NULL) //untill last item of the list is found..
    {
        parent = cursor; //parent equal to current element
        cursor = cursor->next; //current element set to next pointer of current element
    }

    parent->next = NULL; //parent next pointer is now null
}

return head; //return the head of the list
}

I'm not exactly sure if my implication is correct here, but I'm required to return the head of the list, which I do believe I'm doing. Any help would be much appreciated.

Upvotes: 0

Views: 511

Answers (1)

Carl Norum
Carl Norum

Reputation: 225262

  1. You didn't initialize cursor.
  2. Don't leak the node you delete. There should probably be a free() call in here somewhere.
  3. Think about what you need to return if your list has only a single entry.

Upvotes: 1

Related Questions