Δημοσιεύτηκε: 11 Απρ 2012, 20:37
από Ilias95
migf1 έγραψε:Κάνε το αρχικά όπως λες.

Ορίστε μια λύση:

Μορφοποιημένος Κώδικας: Επιλογή όλων
#include <stdio.h>   // printf(), puts(), scanf(), putchar()
#include <stdlib.h> // malloc(), free(), exit(), EXIT_SUCCESS, EXIT_FAILURE
#include <string.h> // strcmp(), strcpy()
#include <ctype.h> // tolower()

#define LEN_WORD (30+1)
#define LEN_ALPHABET 26

typedef struct node {
char word[LEN_WORD];
struct node *next;
} Node;

typedef struct {
Node *head;
int len;
} List;


Node *add_to_list(Node *n, char *s)
{
Node *new_node = malloc(sizeof(Node));

if (new_node == NULL)
return NULL;

strcpy(new_node->word, s);
new_node->next = n;
return new_node;
}

void list_print(Node *n)
{
for (; n != NULL; n = n->next)
printf("%s ", n->word);
putchar('\n');
}

void list_destroy(Node *n)
{
if (n == NULL)
return;

Node *dummy = NULL;
for (; n != NULL; n = dummy) {
dummy = n->next;
free(n);
}
}

void lowerize(int n, char s[n])
{
for (int i = 0; i < n; i++) {
s[i] = tolower(s[i]);
if (!s[i])
return;
}
}


int main(void)
{
char word[LEN_WORD];
List alphabet[LEN_ALPHABET];

for (int i = 0; i < LEN_ALPHABET; i++) {
alphabet[i].head = NULL;
alphabet[i].len = 0;
}

for (;;) {
scanf("%s", word);
lowerize(LEN_WORD, word);

int c = word[0] - 'a';

if (c < 0)
c = 0;
else if (c > LEN_ALPHABET)
c = LEN_ALPHABET;

alphabet[c].head = add_to_list(alphabet[c].head, word);
if (alphabet[c].head == NULL)
goto exit_failure;
alphabet[c].len++;

if (!strcmp(word, "stop"))
break;
}

int num_words = 0;
putchar('\n');

for (int i = 0; i < LEN_ALPHABET; i++) {
if (alphabet[i].len) {
printf("%c (%d words): ", i + 'a', alphabet[i].len);
list_print(alphabet[i].head);
num_words += alphabet[i].len;
list_destroy(alphabet[i].head);
}
}
printf("\nyou have typed %d words in total (including \"stop\")\n", num_words);
exit(EXIT_SUCCESS);

exit_failure:
for (int i = 0; i < LEN_ALPHABET; i++)
list_destroy(alphabet[i].head);
exit(EXIT_FAILURE);
}