我的列表头始终指向尾部。有什么问题?我无法在C中正确创建双向链接列表
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
,所以head -> data = 'qw'
它应该始终保持领先,但它会变为erty,然后在每个循环步骤后变为b和cc。
我在做什么错了?
你是不是要确保旧的最后一个元素指向新的最后一个元素,当你的元素添加到列表中。 – 2013-04-28 18:09:35