cnxxzqedv 2022-10-09 21:11 采纳率: 71.4%
浏览 36
已结题

VS求单链表长度代码发生错误

#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
typedef struct
{
DataType data;
struct Node* next;
}Node;
void InitNode(Node* first) //初始化单链表
{
first = (Node*)malloc(sizeof(Node));
first->next = NULL;
}
void CreaNode(Node* first,DataType n) //头插法创建单链表
{
Node* p;
for (int i = n; i > 0; i--)
{
p = (Node*)malloc(sizeof(Node));
p->data = i;
p->next = first->next;
first->next = p;

}

}
int ListLength(Node* first)
{
Node * p;
int j = 0;
p = first->next;
while (p!= NULL)
{
p = p->next;
j++;
}
return j;
}
int main()
{
int n;
int e;
Node E;

printf("input n:");
scanf("%d", &n);

InitNode(&E);
CreaNode(&E, n);
e = ListLength(&E);
printf("单链表的长度:%d", e);
return 0;

}

img

  • 写回答

1条回答 默认 最新

  • qzjhjxj 2022-10-09 22:05
    关注

    修改处见注释,供参考:

    #include <stdio.h>
    #include <stdlib.h>
    typedef int DataType;
    typedef struct node //修改
    {
        DataType data;
        struct node* next;//struct Node* next; 修改
    }Node;
    void InitNode(Node* first) //初始化单链表
    {
        //first = (Node*)malloc(sizeof(Node)); 修改
        first->next = NULL;
    }
    void CreaNode(Node* first,DataType n) //头插法创建单链表
    {
        Node* p;
        for (int i = n; i > 0; i--)
        {
            p = (Node*)malloc(sizeof(Node));
            p->data = i;
            p->next = first->next;
            first->next = p;
        }
    }
    int ListLength(Node* first)
    {
        Node * p;
        int j = 0;
        p = first->next;
        while (p!= NULL)
        {
            p = p->next;
            j++;
        }
        return j;
    }
    int main()
    {
        int n;
        int e;
        Node E;
    
        printf("input n:");
        scanf("%d", &n);
    
        InitNode(&E);
        CreaNode(&E, n);
        e = ListLength(&E);
        printf("单链表的长度:%d", e);
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

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

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi