我正在尝试编写一个程序,该程序从用户输入中获取一个句子并将其存储在一个链表中。这是我到目前为止所做的,它似乎正在工作,除了当我打印列表时它打印字符串然后进入无限循环打印“垃圾”。你能看出我哪里出错了吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRLENGTH 100
typedef struct node {
char data;
struct node *next;
} node;
int
main(void) {
char str[STRLENGTH];
printf("Enter a string: ");
gets(str);
node *linkedList = NULL;
node *head = NULL;
node *pre = NULL;
int i;
for(i = 0; str[i] != '\0'; i++) {
linkedList = malloc(sizeof(node));
if(str[i] == ' ')
linkedList -> data = 0;
else
linkedList -> data = str[i];
if(pre != NULL)
pre -> next = linkedList;
else
head = linkedList;
pre = linkedList;
}
while(head != NULL) {
printf("%c", head -> data);
head = head -> next;
}
return 0;
}