链接列表创建 - 垃圾输出?

PnP*_*PnP 1 c pointers linked-list data-structures

似乎无法解决为什么我在打印内容时从此链接列表结构获取垃圾输出.

我的目标是在列表中添加任何内容,一些字符串,char by char,它应该反向打印出来.我使用额外的头部+尾部结构的原因是我可以打印出反向输入的订单行.

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 c, char element) {
 if (c.head == NULL) {
    c.head = c.tail = InsertList(element, NULL);
 }else {
    c.head = InsertList(element, c.head);
 }
return c;
}

int main(void) {
 FullList InOrder;
 FullList Reverse;
 InOrder.head = NULL;
 Reverse.head = NULL;
 char c;

  while ((c = getchar() != '.')) {
    InOrder = addToStart(InOrder, c);
 }
  while (InOrder.head->next != NULL) {
    printf("%c", (InOrder.head->c));
    InOrder.head = InOrder.head->next;

}     
return 0;           
}
Run Code Online (Sandbox Code Playgroud)

cod*_*ict 5

问题出在这里:

while ((c = getchar() != '.')) 
Run Code Online (Sandbox Code Playgroud)

它应该是:

while ((c = getchar()) != '.') 
Run Code Online (Sandbox Code Playgroud)

由于!=具有更高的优先级=.

你在做的while ((c = getchar() != '.'))是:

  1. 你通过电话阅读一个角色getchar.
  2. 比较读取的字符是否为句点.
  3. 将比较结果分配给c,因此您c将是01.当你打印出有价值的角色时,1你会看到奇怪的焦点.

另请注意,getchar的返回类型是int,因此您需要将c声明为int.

while (InOrder.head->next != NULL) 
Run Code Online (Sandbox Code Playgroud)

应该:

while (InOrder.head != NULL)
Run Code Online (Sandbox Code Playgroud)

否则你过早地终止循环而不处理最后一个节点.