#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
char *data;
struct Node *next;
} Node;
void add_node(Node **head, Node **tail, char *word)
{
Node *new_node = malloc(sizeof(Node));
if (new_node == NULL) {
free(word);
return;
}
new_node->data = word;
new_node->next = NULL;
if (*head == NULL)
*head = new_node;
else
(*tail)->next = new_node;
*tail = new_node;
}
Node *create_list(void)
{
Node *head = NULL;
Node *tail = NULL;
char *word = NULL;
size_t size = 0;
size_t len = 0;
int c;
while ((c = getchar()) != '\n' && c != EOF) {
if (c == ' ') {
if (len != 0) {
word[len] = '\0';
add_node(&head, &tail, word);
word = NULL;
size = 0;
len = 0;
}
} else {
if (len + 1 >= size) {
size = (size == 0) ? 8 : size * 2;
char *tmp = realloc(word, size);
if (tmp == NULL) {
free(word);
return head;
}
word = tmp;
}
word[len++] = (char)c;
}
}
if (len != 0) {
word[len] = '\0';
add_node(&head, &tail, word);
} else {
free(word);
}
return head;
}
void print_list(const Node *head)
{
while (head != NULL) {
printf("%s", head->data);
if (head->next != NULL)
printf(" ");
head = head->next;
}
printf("\n");
}
void delete_list(Node **head)
{
while (*head != NULL) {
Node *tmp = *head;
*head = (*head)->next;
free(tmp->data);
free(tmp);
}
}
int main(void)
{
Node *list = create_list();
print_list(list);
delete_list(&list);
return 0;
}