Parch
Parch

Reputation: 17

Having a hard time creating a function for lists in C

I am trying to create a function delz() which deletes a given number from the end of the list, I tried recursively and with a while loop and I can't figure it out. Example: [ 3 | next ] - [ 4 | next ] - [ 3 | next ] - [ 7 | next ] -----> [ 3 | next ] - [ 4 | next ] - [ 7 | next ]

list delz (int val, list l) {
    if(l == NULL)
        return NULL;
    else {
        list head = l;
        list tmp = l;
        list tail;
        list temp;
        while(l != NULL){
            if(l->value == val) {
                list tail = l->next;
                head->next = tail;
            }
            temp = head;
            head = tmp;
            l = l->next;
        }
        return head;
    }
}


typedef struct node {
int value;
struct node *next;
} node, *list;

Upvotes: 1

Views: 49

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

The function will be simpler if to pass to the function the pointer to the head node by reference.

Here is a demonstrative program. I used my own singly-linked list definition because you did not show your own. Also it is a bad idea to introduce a typedef for a pointer type.

#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int val;
    struct Node *next;
};

void assign( struct Node **head, const int a[], size_t n )
{
    if ( *head )
    {
        struct Node *tmp = *head;
        *head = ( *head )->next;
        free( tmp );
    }

    for ( size_t i = 0; i < n; i++ )
    {
        *head = malloc( sizeof( struct Node ) );
        ( *head )->val = a[i];
        ( *head )->next = NULL;
        head = &( *head )->next;
    }
}

void display( const struct Node *head )
{
    for ( ; head != NULL; head = head->next )
    {
        printf( "%d -> ", head->val );
    }

    puts( "null" );
}

int remove_last( struct Node **head, int val )
{
    struct Node **target = NULL;

    for ( ; *head != NULL; head = &( *head )->next )
    {
        if ( ( *head )->val == val ) target = head;
    }

    int success = target != NULL;

    if ( success )
    {
        struct Node *tmp = *target;
        *target = ( *target )->next;
        free( tmp );
    }

    return success;
}

int main(void) 
{
    int a[] = { 3, 4, 3, 7 };
    const size_t N = sizeof( a ) / sizeof( *a );

    struct Node *head = NULL;

    assign( &head, a, N );

    display( head );

    int val = 3;

    if ( remove_last( &head, val ) )
    {
        printf( "The last node with the value %d is removed.\n", val );
    }

    display( head );

    return 0;
}

The program output is

3 -> 4 -> 3 -> 7 -> null
The last node with the value 3 is removed.
3 -> 4 -> 7 -> null

Upvotes: 1

Related Questions