鱼C论坛

 找回密码
 立即注册
查看: 478|回复: 1

为什么这个链表会出错

[复制链接]
发表于 2024-2-28 20:55:38 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include<stdio.h>
#include<malloc.h>
struct lian{
        int score;
        struct lian *next;
};
typedef struct lian link;
link create(link *head,int n){//存疑
        int i=0;
        link *tail,*node;
        tail = head;
        for(i=0;i<n;i++){
                head = (link *)malloc(sizeof(link));
                printf("请输入第%d个数字:\n",i+1);
                scanf("%d",&node->score);
               
                tail->next=node;
                tail = node;
        }
        node->next=NULL;
        return *head;
}
link look(link *head){
        link *tail;
        int i=0;
        tail = head;
        while(tail){
                i++;
                tail = tail->next;
                printf("第%d个为%d\n",i,tail->score);

        }
        return *head;
}
int main(){
        int n;
        link *head;
        scanf("%d",&n);
        create(head,n);
        look(head);
        return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-2-28 20:56:14 | 显示全部楼层
这段代码中出现了几个问题。

首先,在包含头文件的地方,没有写入正确的头文件。应该添加 `#include <stdio.h>` 和 `#include <stdlib.h>` 来包含标准输入输出和动态内存分配的相关函数。

其次,在 `create` 函数中,使用了一个指向 `link` 结构体指针的指针来接收传入的链表头指针,并且在创建新节点时也使用了一个错误的指针类型。正确的做法是直接传入链表头结点的指针,并且在创建新节点时使用 `link *node = (link *)malloc(sizeof(link))`。

最后,在 `look` 函数中,在 `while` 循环中应该先打印当前节点的数据再移动到下一个节点,否则会导致在打印时指针已经移动到了下一个节点的位置。此外,在循环结束后需要释放链表内存。

下面是修改后的代码:
#include <stdio.h>
#include <stdlib.h>

struct lian {
    int score;
    struct lian *next;
};
typedef struct lian link;

link* create(link *head, int n) {
    int i = 0;
    link *tail, *node;
    tail = head;
    for (i = 0; i < n; i++) {
        node = (link *)malloc(sizeof(link));
        printf("请输入第%d个数字:", i+1);
        scanf("%d", &(node->score));
        
        tail->next = node;
        tail = node;
    }
    node->next = NULL;
    return head;
}

void look(link *head) {
    link *tail;
    int i = 0;
    tail = head;
    while (tail->next) {
        tail = tail->next;
        i++;
        printf("第%d个为%d\n", i, tail->score);
    }
}

int main() {
    int n;
    link *head;
    
    printf("请输入链表的长度:");
    scanf("%d", &n);
    
    head = (link *)malloc(sizeof(link));
    head->next = NULL;
    
    create(head, n);
    look(head);

    // 释放链表内存
    link *temp;
    while (head) {
        temp = head;
        head = head->next;
        free(temp);
    }

    return 0;
}

在主函数中,我们创建了一个头节点,并将头节点传入 `create` 函数进行链表的创建。最后,在释放链表内存时,我们使用了一个临时指针 `temp` 来遍历链表并释放每一个节点的内存空间。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-30 14:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表