首页 > 解决方案 > 使用 txt 文件填充循环双链表

问题描述

我得到了一个名为 .txt 的 txt 文件circle.txt。此 txt 文件由名称和衬衫号码组成,例如

Cameron 1
David 2
Dorothy 3
Heather 4

等等...到100

所以我必须做一个基于游戏计数的项目,该项目的一部分需要使用该函数为指定数量的玩家创建一个循环双链表void createGame(char* gameFile, int numOfPlayers);,以便每个链接代表一个玩家。然后我必须根据从文件中读取的值设置球员的姓名和球衣号码。所以我的具有所有功能的头文件看起来像

countOust.h

#ifndef CountOust_h
#define CountOust_h

struct listNode
{
    int hName; //represents numbers in file
    char data[15]; // represents name in file
    struct listNode *next;
    struct listNode *prev;

};
typedef struct listNode sNode;

void createGame(char *gameFile, int numOfPlayers);
//void traverseFwd(sNode *list);
//void insertAt(sNode *list, sNode *player);
//void lRemove(sNode *player);
//void traverseBwd(sNode *list);
//void startGame();

#endif

有些函数被注释掉了,因为主要关注的是createGame函数。

因此,我尝试使用for 循环填充countOust.c列表中的链接。我试过类似的东西fopenfscanf

countOust.c

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <stdbool.h>
#include "CountOust.h"

void createGame(char *gameFile, int numOfPlayers)
{
    FILE* f;
    f = fopen(gameFile, "r");

   // head = (struct sNode *)malloc(sizeof(sNode);

    fscanf(f, "%s %d", head->data, &head->hName);

    for (int i = 0; i < numOfPlayers - 1; i++)
    {


    }


    fscanf(f, "%s %d", tail->data, &tail->hName);


}

^这给出了一个错误,因为它的头脑风暴代码

我需要一个 fscanf ,它将包含一个字符串和整数,表示文件中的名称和文件中的数字。

我需要为一个节点设置 malloc 空间,并且该节点应该具有对下一个节点的名称编号引用和对上一个节点的引用。然后我需要设置名称和编号,然后设置上一个和下一个节点的指针。

那么我将如何创建一个循环双链表并使用 fscanf、malloc 为球员姓名和球衣号码填充一个 txt 文件,引用我的头文件结构中的节点,以从 txt 文件创建一个循环双链表?

标签: calgorithmdata-structures

解决方案


假设它gamefile包含您的circle.txt文件名,您的fscanf()调用将只读取当前写入的数字。您还需要添加一些内容来读取名称。

fscanf(f, "%s %d", args...)将是一个很好的起点。


推荐阅读