我的列表头总是指向尾巴。有什么问题?
我的linked_list.h
:
#ifndef LINKED_LIST
#define LINKED_LIST
struct node
{
char *data;
struct node *nextElement;
struct node *prevElement;
};
void createList(struct node **head, struct node **tail);
void fill_list (char *word, struct node **head, struct node **tail);
#endif
main.c
:
#include <stdio.h>
#include <stdlib.h>
#include "linked_list.h"
#include <string.h>
int main()
{
FILE *dataFile;
char *word = (char *) calloc ( 255, sizeof(char) );
/* Create empty list */
struct node *head, *tail;
createList (&head, &tail);
/*------------------------*/
/* Data file open*/
dataFile = fopen("data.txt" ,"r");
if( dataFile == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
/* Data reading */
while (( fscanf(dataFile, "%s", word) ) != EOF )
{
int i = 0;
int wordsCount = 0;
for (i = 0; i <= strlen(word); i++)
{
if ( (word[i] >= 'a') && (word[i] <= 'z') )
wordsCount = wordsCount + 1;
}
if ( wordsCount == strlen(word) )
{
fill_list ( word, &head, &tail );
}
}
fclose(dataFile);
return 0;
};
和linked_list.c
:
#include <stdio.h>
#include <stdlib.h>
#include "linked_list.h"
void createList(struct node **head, struct node **tail)
{
*head = NULL;
*tail = NULL;
}
void fill_list ( char *word, struct node **head, struct node **tail )
{
struct node *elem, *temp;
if ( (*head) == NULL )
{
// printf("HEAD = NULL\n");
elem = (struct node *) malloc ( sizeof (struct node) );
elem -> data = word;
elem -> nextElement = NULL;
elem -> prevElement = NULL;
(*head) = elem;
*tail = elem;
// printf("%s\n", (*head) -> data );
}
else
{
// printf("HEAD != NULL\n");
elem = (struct node *) malloc ( sizeof (struct node) );
elem -> data = word;
elem -> nextElement = NULL;
elem -> prevElement = *tail;
*tail = elem;
// printf("%s\n", (*head) -> data );
}
}
我的数据文件:qw erty b cc。首先,head == NULL
, sohead -> data = 'qw'
并且它应该一直是 head,但它会在每个循环步骤后变为 erty,然后是 b 和 cc。
我做错了什么?