C: remove recursively elements of a list

  • C/++/#
  • Thread starter RaamGeneral
  • Start date
  • #1
Hello.

It's given the following type (sorry for the mix italian-english):

Code:
struct El{
    int info;
    struct El* next;
};

typedef struct El ElementoLista;
typedef ElementoLista* ListaDiInteri;
And I have to remove all elements of value n; I did this:


Code:
void remLista(ListaDiInteri *l, int n)
{
    if((*l)->next==NULL) {(*l)=NULL; return;}
    if((*l)->info==n) {*l=(*l)->next; remLista(&((*l)->next),n);}
    else remLista(&((*l)->next),n);

}
I dislike the use of those pointers. Is there any other way or something?

Thank you.


This is the full code if you want to try:

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


struct El {
    int info;
    struct El *next;
};

typedef struct El ElementoLista;
typedef ElementoLista* ListaDiInteri;

void pushBack(ListaDiInteri *l, int n);
void printLista(ListaDiInteri l);
void remLista(ListaDiInteri *l, int n);



int main()
{

    ListaDiInteri l=NULL;

    pushBack(&l,1);
    pushBack(&l,2);
    pushBack(&l,4);
    pushBack(&l,6);
    pushBack(&l,1);
    pushBack(&l,4);
    pushBack(&l,5);
    pushBack(&l,1);
    pushBack(&l,3);
    pushBack(&l,1);





    printLista(l);

    remLista(&l,1);

    printLista(l);



    return 0;
}


void pushBack(ListaDiInteri *l,int n)
{

    if(*l==NULL){
        *l=malloc(sizeof(ElementoLista));
        (*l)->info=n;
        (*l)->next=NULL;
        return;
    }

    if((*l)->next==NULL){
        ElementoLista *e=malloc(sizeof(ElementoLista));
        e->info=n;
        e->next=NULL;
        (*l)->next=e;
    }
    else pushBack(&((*l)->next),n);
}

void printLista(ListaDiInteri l)
{

    if(l==NULL) printf("Lista vuota\n");

    if(l->next==NULL){
        printf("%d\n",l->info);
        return;
    }
    else{
        printf("%d ",l->info);
        printLista(l->next);
    }

}


void remLista(ListaDiInteri *l, int n)
{
    if((*l)->next==NULL) {(*l)=NULL; return;}
    if((*l)->info==n) {*l=(*l)->next; remLista(&((*l)->next),n);}
    else remLista(&((*l)->next),n);

}

As you can see I have the same problem with pushBack().
 

Answers and Replies

  • #3
I know about the missing free; I need to learn this in C for the exam.
 
  • #4
Is remLista for removal?
Then, look at your pushBack. When do you use malloc?
Free
is the symmetric operation: you are to deallocate your node.

Here you can find the thorough instructions both for recursive and iterative implementation: https://www.cs.bu.edu/teaching/c/linked-list/delete/
 

Related Threads on C: remove recursively elements of a list

Replies
4
Views
686
Replies
9
Views
632
Replies
13
Views
2K
  • Last Post
Replies
12
Views
80K
Replies
26
Views
4K
  • Last Post
Replies
8
Views
445
Replies
1
Views
352
  • Last Post
Replies
5
Views
4K
Top