c - 附加到链表时进行了不必要的更改
问题描述
AI 已经设法让链表发挥作用,因为它可以在其中创建一个列表存储变量,但现在我遇到了另一个我从未找到解决方案的问题。每当我通过我想要存储的变量列表运行它时,它将通过列表运行并创建正确数量的节点,但字符串变量在每次追加后都会不断变化。
例如,如果我运行:
"Dog" "cat" "house"
而不是所需的输出:
Dog
cat
house
它产生
house
house
house
我不确定它为什么一直这样做,而且我似乎无法确定头节点字符串正在被更改的位置,除非第一个实例列表为空,因此需要分配一个新的头。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#define EMPTY NULL;
typedef struct listnode{
struct listnode* next;
char* fileName;
} listnode;
struct listnode* head;
//This section of code will be dedicated to the creation and management
//of the listnode functions
listnode* createNode(char* str, listnode* next){
listnode* tempo;
tempo = (listnode*)malloc(sizeof(struct listnode));
if(tempo == NULL){
printf("Error creating space for new node.\n");
exit(0);
}
tempo->fileName = str;
tempo->next = next;
return tempo;
}
listnode* append(listnode* head, char* str){
listnode* temp;
listnode* curr;
temp = createNode(str, NULL);
if(head == NULL){
head = temp;
return head;
}
else{
curr = head;
while(curr->next != NULL){
curr = curr->next;
}
curr->next = temp;
return head;
}
}
void printNames(listnode* head){
listnode* curr= head;
while(curr !=NULL){
printf("%s \n", curr->fileName);
curr = curr->next;
}
}
void list_free(listnode* head){
listnode* current;
listnode* temp;
if(head != NULL){
current = head->next;
if(head !=NULL){
current = head -> next;
head ->next = NULL;
while(current != NULL){
temp = current -> next;
free(current);
current = temp;
}
}
}
free(head);
}
int main(int argc, char **argv){
char *current_dir = NULL;
DIR *direct_ptr = NULL;
struct dirent *dir_ptr = NULL;
unsigned int fileNum = 0;
int c;
listnode* head = NULL;
current_dir = getenv("PWD");
if(NULL == current_dir){
printf("\n Error: Couldn't grab current directory.\n");
return -1;
}
direct_ptr = opendir((const char*)current_dir);
if(NULL == direct_ptr){
printf("\n Error: couldn't open current directory\n");
return -1;
}
for(fileNum=0; NULL != (dir_ptr = readdir(direct_ptr)); fileNum++){
if(dir_ptr->d_name[0] != '.'){
head = append(head, dir_ptr->d_name);
}
}
printNames(head);
}
解决方案
推荐阅读
- react-native - 审查验证在 react-native 中失败
- mysql - 在 mysql 的单个查询中获取过去 24 小时的总和和总和
- c# - 如何在C#中的数组内的一行中找到最大相同字符数
- regex - Matlab:简单的正则表达式使用问题
- node.js - 发生错误时如何使用 Sequelize ORM 作为 SHOW INDEX FROM `user_roles`
- java - org.apache.kafka.common.errors.TopicAuthorizationException:无权访问主题:
- python - 如何在python中的多个点拆分字符串
- mongodb - MongoDB 计算一组过滤文档集中每个值的出现次数
- ruby - Ruby 中的子类构造函数
- reactjs - 无法将我的 AWS api 网关与我的本地主机连接