Хорошо, у меня было время понять, почему мой первый ответ не сработает - несколько небольших очевидных вещей, если вы запускаете код через отладчик.Итак, вот полностью рабочая версия.Возможно, его можно было бы немного оптимизировать, но он следует той же структуре, что и ваш исходный код, поэтому, надеюсь, вы сможете следовать ему:
typedef struct L {
char val;
struct L *next;
struct L *prev;
} List;
List* insertList( char val, List *t1 ) {
List *t = calloc(1, sizeof( List ));
t->prev = NULL;
t->val = val;
t->next = t1;
if (t1 != NULL)
t1->prev = t;
return t;
}
List* createList( void ) {
List *h = NULL;
char c;
do {
c =(char)getchar();
h = insertList( c, h );
} while (c != '.');
return h;
}
void freeList( List *list ) {
// free the linked list
if (list != NULL) {
freeList( list->next );
free( list );
}
}
int main( void ) {
// create list
List *head = createList();
List *pos = head, *currentChar = NULL, *wordStart = NULL;
while (pos != NULL)
{
// find next word
wordStart = NULL;
while (pos != NULL)
{
// gone past the beginning of a word yet?
if ((pos->val == '\n') || (pos->next == NULL))
{
wordStart = (pos->next == NULL) ? pos : pos->prev; // note where this word starts
pos = pos->next; // jump over \n, or go to end of list (null), for next time into this loop
break; // jump out of this loop so we can output the word
}
else // not found end of word yet - on to next char
pos = pos->next;
}
// have we found a word? if so, output it!
if (wordStart != NULL)
{
currentChar = wordStart; // start at first char in the word
while (currentChar != NULL)
{
printf( "%c", currentChar->val ); // output this char
currentChar = currentChar->prev; // on to next char in the word
if ((currentChar != NULL) && (currentChar->val == '\n'))
break; // stop after last char of the word
}
// print the line-feed just before wordStart (if there is one)
if (wordStart->next != NULL)
printf( "%c", wordStart->next->val );
}
else // we've reached the end - stop
break; // not really necessary - pos should be NULL at this point anyway
}
freeList( head ); // free linked list memory
return 0;
}
Основное изменение - это способ вывода перевода строки.Я понял, что это НЕ перевод строки после каждого нужного вам слова, а тот, который ДО ТОГО, как он (не совсем логично - интересно, так ли это изначально предполагалось в вопросе?).Но теперь он выводит именно то, что вам нужно.И я добавил функцию для освобождения памяти связанного списка в конце тоже для вас.:)