【发布时间】:2011-11-26 13:35:51
【问题描述】:
基本上问题是,我想要这样的输入:
Hello
World
.
要以相反的字序输出:
World
Hello
但我的代码似乎输出了
orldello
错过了\n 和每个单词的第一个字母,我不知所措!
这是我迄今为止尝试过的:
typedef struct List {
char c;
struct List *next;
} List;
typedef struct {
List *head;
List *tail;
} FullList;
List* InsertList(int hd, List* t1) {
List *t = (List*)calloc(1,sizeof(List));
t->c = hd;
t->next = t1;
return t;
}
FullList addToStart(FullList c1, char element) {
if (c1.head == NULL) {
c1.head = c1.tail = InsertList(element, NULL);
} else {
c1.head = InsertList(element, c1.head);
}
return c1;
}
int main(void) {
FullList InOrder;
FullList Reverse;
InOrder.head = NULL;
Reverse.head = NULL;
char c;
while ((c = getchar()) != '.') {
while((c = getchar()) != '\n') {
InOrder = addToStart(InOrder,c);
}
while ((InOrder.head) != NULL ) {
Reverse = addToStart(Reverse, InOrder.head->c);
InOrder.head = InOrder.head->next;
}
}
while(Reverse.head != NULL) {
printf("%c", Reverse.head->c);
Reverse.head = Reverse.head->next;
}
return 0;
}
【问题讨论】:
-
好吧,首先,您永远不会将 \n 添加到列表中...
-
嗯,但问题是,我需要将单词逐个添加到反向列表中,以便它们以相反的顺序出来,我想不出另一个终止条件。跨度>
-
然后使用 do {} while 循环,以便在将字符添加到列表后检查 \n,因此只有在添加了 \n 后才会跳出循环。
-
现在我似乎打印出了 WorldHello,但仍然缺少一个 \n,尽管它解决了缺少第一个字符的问题。
-
任何线索,尼克,似乎仍然无法正常工作
标签: c linked-list