【问题标题】:Linked List Query链表查询
【发布时间】: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


【解决方案1】:

因此,您不会存储换行符:

while((c = getchar()) != '\n')

只要读取的字符不是换行符,循环体就会重复。换行时,循环中的代码被执行。

每行的第一个字符被删除,因为您这样做:

while((c = getchar()) != '.') {
    while((c = getchar()) != '\n') {

您读取了一个字符,对它不做任何事情,再次读取一个字符,然后将其附加到列表中。只需摆脱内部循环,它应该可以正常工作。

编辑: 我误解了这个问题。如果要反转行的顺序,请不要将每个字符作为元素添加到列表中。将列表元素的类型从char更改为char*,并将每一行存储为一个元素:

char buff[500];
fgets(buff, 500, stdin);
char *new_element = strdup(buff);
/* Add new_element to the list */

【讨论】:

  • 我不能删除内循环,否则它不会反转我的输入。
  • 我输入 Hello\nWorld\n。它将它存储在我的列表 n\dlorWn\olleH 中。因此,内部循环可以确保它逐字翻转我的输入,并打印出来。
【解决方案2】:

我相信这就是您想要实现的目标。您总是追加到列表的“中间”,如果找到换行符,则将列表的中间设置为头指针。

FullList l;
Lust* ins = l.head = insertList(NULL,0); // sentinel
while ((c = getchar()) != '.') {
  ins = ins->next = insertList(ins->next,c);
  if (c == '\n') {
    ins = l.head;
  }
}
ins = l.head;
free(l.head);
l.head = ins;

请注意,尾指针未使用,也从未设置为正确的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多