首页 > 解决方案 > 使用文件流中的数据创建单链表

问题描述

我目前正在尝试创建一个程序,该程序将在每个节点中创建一个包含以下内容的链表:

  1. 指向下一个节点的指针(显然需要)
  2. 从文件流中的一行文本读入的字符串
  3. 在文件流中遇到字符串的次数

我有以下代码,但是我遇到了一些我显然无法掌握的问题:

  1. 如果在列表中没有找到相应的节点,如何搜索列表然后创建一个节点?

  2. 一般来说,如何创建头节点,然后开始将后续节点链接到它?

非常感谢任何帮助,因为我花了很多时间在谷歌上搜索和观看 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;
}

标签: csingly-linked-list

解决方案


推荐阅读