我的列表頭始終指向尾部。有什麼問題?我無法在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