gpt4 book ai didi

将字符串转换为链接列表

转载 作者:行者123 更新时间:2023-11-30 17:50:20 25 4
gpt4 key购买 nike

1)我需要从文件中读取字符串并将该字符串转换为链接列表

所以...如果我读入这个字符串“Some String”

链接列表将如下所示

节点1 - “S”

节点2 - “o”

节点3 - “m”

节点4 - “e”

节点5 - NULL

节点6 - “S”

节点7 - “t”

node8 - “r”

node9 - “我”

节点10 - “n”

node11 - “g”

node12 - NULL

对于“”(空格)和“\0”空字符,将发出 NULL

实现这个的最佳方法是什么..

typedef struct node
{
// each node holds a single character
char data;

// pointer to next node in linked list
struct node *next;
} node;

int i;
char buffer[1032];

FILE *ifp = fopen("file.txt", "rb");

//read the first line of file
fscanf(ifp, "%s", buffer);

node *myList = malloc(sizeof(node));

for(i = 0; i < strlen(buffer); i++)
/*I DON'T KNOW WHAT TO DO HERE!!!!*/

在这里我迷路了,或者如果我的实现完全错误,请告诉我

最佳答案

你的fscanf(ifp, "%s", buffer);将在读取“Some”后停止。我使用fgets()代替。在手册中(man fgets):

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.

最后一个“\0”可以方便地将缓冲区作为字符串处理。所以我在 FILE *ifp = fopen("file.txt", "rb"); 之后的代码是:

fgets(buffer,1032-1,ifp);
node *myList,*head,*pre = NULL;

for(i = 0; buffer[i] != '\0' ; i++) {
myList = malloc(sizeof(node));
myList->data = buffer[i];
if(pre!=NULL)
pre->next = myList;
else
head = myList;
pre = myList;
}

while(head!=NULL) {
printf("%c\n",head->data);
head=head->next;
}
fclose(ifp);

你的工具将'\n'和空格存储为NULL,当你更改时就可以了

myList->data = buffer[i];

if(buffer[i]=='\n' || buffer[i]==' ')
myList->data = 0;
else
myList->data = buffer[i];

关于将字符串转换为链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17332410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com