删除最后一个链接列表

时间:2011-06-02 04:36:31

标签: c linked-list

我似乎无法摆脱额外的链接列表。我知道有很多方法可以做到这一点,但我只是想以一种简单的方式释放它,因为它是在我的循环中创建的额外的。这是代码:

    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;
    }

2 个答案:

答案 0 :(得分:1)

替换代码的最后部分
prev= NULL;
current = first =...
...
} //end if
prev = current;
current = current->next;
} //end while

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

答案 1 :(得分:0)

一种方法是永远不要创建额外的节点。从文件读取到临时变量,并且在您知道需要它之前不要创建下一个节点。

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);
}
相关问题