在 C 中创建单向链表

标签 c linked-list singly-linked-list

我正在尝试从输入文本文件创建单向链表以进行作业。我试图一次做一点,所以我知道我的代码不完整。我尝试创建头指针并打印出它的值,但我什至无法让它工作,但我不确定为什么。我包含了结构、我的创建列表和打印列表函数。我没有包含打开的文件,因为那部分有效。

typedef struct List
{
   struct List *next;   /* pointer to the next list node */
   char *str;           /* pointer to the string represented */
   int count;           /* # of occurrences of this string */
} LIST;

LIST *CreateList(FILE *fp) 
{
    char input[LINE_LEN];
    LIST *root;             /* contains root of list             */
    size_t strSize;         
    LIST *newList;          /* used to allocate new list members */

    while (fscanf(fp, BUFFMT"s", input) != EOF) {

        strSize = strlen(input) + 1;

        /* create root node if no current root node */
        if (root == NULL) {
            if ((newList = (LIST *)malloc(sizeof(LIST))) == NULL) {
                printf("Out of memory...");
                exit(EXIT_FAILURE);
            } 
            if ((char *)malloc(sizeof(strSize)) == NULL) {
                printf("Not enough memory for %s", input);
                exit(EXIT_FAILURE);
            }
                memcpy(newList->str, input, strSize);   /*copy string    */
                newList->count = START_COUNT;
                newList->next = NULL;
                root = newList;
        }
    }
        return root;
}

/* Prints sinly linked list and returns head pointer */
LIST *PrintList(const LIST *head) 
{
    int count;

    for (count = 1; head != NULL; head = head->next, head++) {
        printf("%s    %d", head->str, head->count);
    }                       
    return head;     /* does this actually return the start of head ptr, b/c I want to 
                            return the start of the head ptr. */
}

最佳答案

root 有一个未定义的值,所以它不会初始化。 CreateList的第二行应该是

LIST *root = NULL;

此外,在更下方显然有分配项的详细信息,但是 a) 代码无法捕获分配并将其保存在任何地方,以及 b) 分配的大小应为 strSize,不是变量本身的长度。有几种方法可以修复它,但最直接的方法是:

newList->str = (char *)malloc(strSize);
if (newList->str == NULL)

关于在 C 中创建单向链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2309359/

相关文章:

c - openssl 无法让 ENGINE_by_id() 工作

c - 这段关于线程的 C 代码应该如何工作?

java - 有没有办法通过链表末尾的索引找到链表中的元素

C - 显示期间链表段错误

c - 链表追加最后一次不起作用

c++ - 遍历链表插入 STL vector 值

c++ - C/C++ 很酷的宏定义?

c - 如何从 argv 将整数传递到 pthread_create 函数? (C)

java - 递归地反转Java中的链表

java - 如何从java中的链接列表中的节点检索对象的内容