小灬丶胖次503 2022-05-09 23:16 采纳率: 100%
浏览 45
已结题

链表为什么只输出最后一个节点

构建了一个有头结点的链表,输出的时候 只输出了头结点和最后一个节点的内容
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define wen "C:\Users\123\Desktop\WYT.txt"
typedef struct link {
struct link* before;
int cont;
int num;
struct link* next;
}Link;
void add1(Link* tail, int cont, int num);
int main() {
Link* head;
Link* tail;
head =(Link*) malloc(sizeof(Link));
tail = head;
int a, b;
scanf_s("%d %d", &a, &b);
while (a != -1) {
add1(tail, a, b);
scanf_s("%d %d", &a, &b);

}
while (head != NULL)
{
    printf("%d %d", head->cont, head->num);
    head = head->next;
}

}
void add1(Link* tail, int cont, int num) {
Link* p;
p = (Link*)malloc(sizeof(Link));
p->cont = cont;
p->num = num;
p->next = NULL;
tail->next = p;
tail = tail->next;
}

  • 写回答

2条回答 默认 最新

  • qzjhjxj 2022-05-10 00:03
    关注

    修改处见注释,供参考:

    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    #define wen "C:\\Users\\123\\Desktop\\WYT.txt"//修改
    typedef struct link {
        struct link* before;
        int cont;
        int num;
        struct link* next;
    }Link;
    void add1(Link** tail, int cont, int num); //修改
    int main()
    {
        Link* head;
        Link* tail;
        head =(Link*) malloc(sizeof(Link));
        head->next = NULL;
        tail = head;
        int a, b;
        scanf("%d %d", &a, &b);
        while (a != -1) {
            add1(&tail, a, b); //修改
            scanf("%d %d", &a, &b);
        }
        while (head->next != NULL)  //(head != NULL)修改
        {
            printf("%d %d  ", head->next->cont, head->next->num); //修改
            head = head->next;
        }
    
        return 0;
    }
    void add1(Link** tail, int cont, int num)//修改
    {
        Link* p;
        p = (Link*)malloc(sizeof(Link));
        p->cont = cont;
        p->num = num;
        p->next = NULL;
        (*tail)->next = p;//修改
        (*tail) = (*tail)->next;//修改
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 5月18日
  • 已采纳回答 5月10日
  • 创建了问题 5月9日

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号