【发布时间】:2020-12-11 14:38:20
【问题描述】:
我一直在做一个项目,我正在为它搞清楚后勤工作,所以我在将它们实施到实际程序之前先制作基本功能。我一直在构建一个大链表,其中包含从名为 words.txt 的 txt 文件中读取的一组单词。在阅读了这些单词并将它们放入链接列表之后,我一直在尝试让一些功能正常工作,但我做不到。第一个是从链表中搜索一个字符串,并在打印列表的其余部分后打印它。 (我不需要为我的程序打印单词我只需要找到它,但现在,我正在打印它来测试功能。)第二个是从链接列表中删除我搜索的单词.在源代码中,我只包含了尝试搜索单词的代码,因为我完全删除了删除功能,因为我想从头开始。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*Node of linked list*/
typedef struct node {
char *data;
struct node *next;
} node;
node *start = NULL;
node *current;
/*Void function to print list*/
void printList(struct node *node)
{
while (node != NULL) {
printf("%s ", node->data);
node = node->next;
}
}
/*Appending nodes to linked list*/
void add(char *line) {
node *temp = malloc(sizeof(node));
temp->data = strdup(line);
temp->next = NULL;
current = start;
if(start == NULL) {
start = temp;
} else {
while(current->next != NULL) {
current = current->next;
}
current->next = temp;
}
}
void readfile(char *filename) {
FILE *file = fopen(filename, "r");
if(file == NULL) {
exit(1);
}
char buffer[512];
while(fgets(buffer, sizeof(buffer), file) != NULL) {
add(buffer);
}
fclose(file);
}
node *listSearch(node* start, char nodeSearched){
node *p;
for (p = start; p != NULL; p = p->next)
if (strcmp(p->data, nodeSearched) == 0)
printf("%s", p);
return NULL;
}
int main(){
readfile("words.txt");
printList(start);
listSearch(start, "word");
return 0;
}
【问题讨论】:
-
node *listSearch(node* start, char nodeSearched){不应该是:node *listSearch(node* start, char* nodeSearched){吗?第二个参数应该是char*而不是char,不是吗? -
我这样做了,但还是不行
-
我不是在告诉你该怎么做,我是在要求澄清。我想你在将代码复制到问题时可能犯了一个错误。
标签: c singly-linked-list