Ko_no_Dio_da666 2021-05-23 11:32 采纳率: 75%
浏览 43
已采纳

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

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

  • 写回答

4条回答 默认 最新

  • benbenli 2021-05-23 13:06
    关注

    循环条件改为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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵