c - 使用文件流中的数据创建单链表
问题描述
我目前正在尝试创建一个程序,该程序将在每个节点中创建一个包含以下内容的链表:
- 指向下一个节点的指针(显然需要)
- 从文件流中的一行文本读入的字符串
- 在文件流中遇到字符串的次数
我有以下代码,但是我遇到了一些我显然无法掌握的问题:
如果在列表中没有找到相应的节点,如何搜索列表然后创建一个节点?
一般来说,如何创建头节点,然后开始将后续节点链接到它?
非常感谢任何帮助,因为我花了很多时间在谷歌上搜索和观看 youtube 视频无济于事。
typedef struct List
{
struct List *next;
char *str;
int count;
} List;
以上来自提供的头文件。以下是我当前的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "C2A6E4_List-Driver.h"
#define ARRAY_SIZE 255 /*Define the size of the array*/
List *CreateLinkedList(FILE *fp)
{
List *head, *ptr, *p;
head = NULL;
char tempBuffer[ARRAY_SIZE];
while (fgets(tempBuffer, ARRAY_SIZE, fp) != NULL)
{
char *strToken = strtok(tempBuffer, " ");
while (strToken != NULL)
{
for (p = head; p != NULL; p = p->next)
;
if (strcmp(p->str, strToken) == 0)
{
p->count++;
break;
}
else
{
if ((ptr = (List *)malloc(sizeof(List))) == NULL)
{
fprintf(stderr, "Failed to allocate memory!");
exit(EXIT_FAILURE);
}
if ((ptr->str = (char *)malloc(strlen(strToken) * sizeof(char) + sizeof(char))) == NULL)
{
fprintf(stderr, "Failed to allocate memory!");
exit(EXIT_FAILURE);
}
memcpy(&ptr->str, &strToken, sizeof(strToken));
ptr->count = 1;
if (head != NULL)
{
p = head;
p->next = ptr;
}
else
head = ptr;
}
strToken = strtok(NULL, " ");
}
}
return head;
}
解决方案
推荐阅读
- javascript - 仅在使用 useEffect 卸载组件时执行功能
- algorithm - 如何从 perl 中的列表中获取未知模式?
- ruby-on-rails - 制作下拉菜单并在 Rails 中获取值
- java - 打印数字随着它减少但它跳过了应该打印的东西
- python - 为什么在 Google Colab 中运行此 python 代码时我没有得到任何结果
- c - addrinfo 结构在函数调用后不保留值
- c# - 自定义验证器检查在文本框中输入的年龄
- r - 带有 Cbind 的 xTabs - 将报告的值拆分为子类别
- r - 在 R 中应用带有 group_by 的调整后的箱线图方法 adjboxstats()?
- amazon-web-services - AWS CLI 命令修改/裁剪输出?