链表缺失元素

时间:2013-05-22 21:32:34

标签: c linked-list element

我正在编写一个c程序,我希望根据条件将字符串添加到链表中。由于我的代码很长,我制作了一个简化版本,也显示了我的问题。

我的问题是,在用字符串填充列表后,当我想打印所有元素时,我的“go_thru”函数无法打印列表的最后一个元素。 代码:

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

typedef struct listelement{
    char val[100];
    struct listelement *next;
} LISTELEMENT;

void go_thru( LISTELEMENT *head ){
    LISTELEMENT *temp = head;

    while( temp != NULL ){
        printf("%s ", temp->val);
        temp = temp->next;
    }
}

LISTELEMENT *insert_before( LISTELEMENT *head, char value[] ){
    LISTELEMENT *new_el = ( LISTELEMENT* ) malloc( sizeof( LISTELEMENT ) );

    strcpy( new_el->val, value );
    new_el->next = head;

    return new_el;
}

int main()
{
    LISTELEMENT *list_chi = NULL;
    int i;
    char arr[6][10] = { "cheese",
                        "salt",
                        "icecream",
                        "snow",
                        "summer",
                        "violet"    };
    for( i = 0; i < 6; i++ )
        list_chi = insert_before( list_chi, arr[i] );

    go_thru( list_chi->next );

    return 0;
}

输出包含除“紫色”以外的所有字符串。我google-d很多,寻找答案,甚至尝试在这里搜索btw问题,但仍无法解决问题:/

1 个答案:

答案 0 :(得分:1)

当主要的for循环结束时,你的列表看起来像:

"violet" -> "summer" -> "snow" -> "icecream" -> "salt" -> "cheese" -> [NULL]
/* where -> is a 'next' */

(反向排序是由于insert_before的使用。)考虑到这一点,问题是:

go_thru(list_chi->next); /* ERROR: skips first element! */

为什么呢?好吧,再次使用该图表:

   "violet"    -> "summer"      -> "snow" -> "icecream" -> "salt" -> "cheese" -> [NULL]
/* ^^ list_chi    ^^ list_chi->next */

您可以通过调用go_thru(list_chi)来解决此问题。除此之外,您的代码看起来不错。

相关问题