为什么不能打印出链表的值,请指教

#include #include struct node{ int data; struct node*next; }; struct node*head; struct node*insert(int x){ struct node*a=(struct node*)malloc(sizeof(struct node)); a->data=x; a->next=NULL; return a; }; void insertathead(int x){ struct node*b=insert(x); if(head==NULL) { head=b; return; } b->next=head; head=b; }; void print(){ struct node*c=head; while(c->next!=NULL); { printf("%d\t",c->data); c=c->next; } return; }; int main (void) { head=NULL; insertathead(1); insertathead(2); insertathead(3); print(); return 0; }

循环条件改为while (c != NULL),可以打呀。你看下面的代码和运行结果。


#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node * next;
};

struct node * head;
struct node * insert(int x) {
    //printf("Creating node for data %d\n", x);
    struct node * a = (struct node * ) malloc(sizeof(struct node));
    a -> data = x;
    a -> next = NULL;
    return a;
};

void insertathead(int x) {
    struct node * b = insert(x);
    if (head == NULL) {
        //printf("Head is NULL. %d is head.\n", x);
        head = b;
        return;
    }
    //printf("Head is not NULL. %d is inserted to head.\n", x);
    b -> next = head;
    head = b;
};

void print() {
    struct node * c = head;
    while (c != NULL) {
        printf("%d\t", c -> data);
        c = c -> next;
    }
    return;
};

int main(void) {
    head = NULL;
    insertathead(1);
    insertathead(2);
    insertathead(3);
    print();
    return 0;
}



// Output
3       2       1

 

while(c->next!=NULL);   增加了分号,跟后面的语句就不是一体了,会死循环等待,因为条件一直不成立且不会变化

原因是while (c != NULL); 后面多了一个分号,形成了以各循环体为空的死循环。

 

    while (c != NULL); {
        printf("%d\t", c -> data);
        c = c -> next;
    }

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632