链表创建 - 垃圾输出?
似乎无法弄清楚为什么当我打印内容时,我从这个链接列表结构中得到垃圾输出。
我的目标是将任何内容添加到列表中,一些字符串,一个字符一个字符,并且它应该反向打印出来。我使用 Head + Tail 的额外结构的原因是这样我就可以打印出反向输入的顺序行。
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;
}
Can't seem to work out why I'm getting garbage output from this Linked List structure when I print the contents.
My goal is to add anything to the list, some string, char by char, an it should print it out in reverse. The reason Im using the extra Struct for Head + Tail is so that I can then print out the the order lines were entered in reverse as well.
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题就在这里:
它应该是:
因为
!=
有 更高的优先级< /a> 大于=
。您在
while ((c = getchar() != '.'))
中所做的事情是:getchar
读取一个字符。c
,因此您的c
将是0
或1
。当您打印值为1
的字符时,您会看到那个看起来很奇怪的字符。另请注意, getchar 的返回类型是
int,所以需要将c声明为int。
还
应该是:
否则您会提前终止循环而不处理最后一个节点。
The problem is here:
it should be:
because
!=
has higher precedence than=
.What you are doing in
while ((c = getchar() != '.'))
is:getchar
.c
, so yourc
will be either0
or1
. And when you print the character with value1
you see that weird looking char.Also note that the return type of getchar is
int
, so you need to declare c as int.Also
should be:
else you prematurely terminate the loop without processing the last node.