c - 链表查询

标签 c linked-list

本质上的问题是,我想要这样的输入:

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;           
} 

最佳答案

因此您不存储换行符:

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 */

关于c - 链表查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8278753/

相关文章:

c - 从指针打印?

C 链表追加插入

c - 从头开始用 C 语言编程 ARM

python - 从 C 扩展返回 C 字符串数组

java - 将节点添加到链表末尾

c++ - 为什么链表使用指针而不是在节点内存储节点

c - 在 C 中使用字符串对链表进行排序

c - 从链表中删除节点

C 使用函数重写数组,避免指针

php - 我怎样才能有效地让我的脚本休眠准确的毫秒数?