Julian Hernandez
Julian Hernandez

Reputation: 1

Deleting last linked list

I can't seem to get rid of an extra linked list. I know there are many ways to do it, but i just want to a simple way of freeing it because it was created as an extra in my loop. here's the code:

    current = first = malloc (sizeof (NODE));
    while( fscanf( fin, "%s", current -> seq) != EOF) {
            for (i = 0; i < 300; i++){
                    if (current->seq[i] == 'a')
                            current->seq[i] = 'A';
                    else if (current->seq[i] == 't')
                            current->seq[i] = 'T';
                    else if(current->seq[i] == 'g')
                            current->seq[i] = 'G';
                    else if(current->seq[i] == 'c')
                            current->seq[i] = 'C';
            }
            if ( (current -> next = malloc ( sizeof(NODE) ) ) == NULL){
                    fprintf(fout, "Out of memory\nCan't add more DNA sequences\n");
                    return EXIT_FAILURE;
            }
            current = current -> next;
    }

Upvotes: 0

Views: 128

Answers (2)

Dewb
Dewb

Reputation: 382

One way is to never create the extra node in the first place. Read from the file into a temp variable, and don't create the next node until you know you need it.

NODE* first;
NODE** ppCurrent = &first;

while( fscanf( fin, "%s", temp) != EOF) 
{
    if ((*ppCurrent = malloc(sizeof(NODE))) == NULL)
    {
        fprintf(fout, "Out of memory\nCan't add more DNA sequences\n");
        return EXIT_FAILURE;
    }

    for (i = 0; i < 300; i++)
        temp[i] = toupper(temp[i]);

    (*ppCurrent)->seq = temp;
    ppCurrent = &((*ppCurrent)->next);
}

Upvotes: 0

user209051
user209051

Reputation: 329

replace last part of code with

prev= NULL;
current = first =...
...
} //end if
prev = current;
current = current->next;
} //end while

free(current)
if(prev !=NULL)
prev->next = Null;

Upvotes: 1

Related Questions