鱼C论坛

 找回密码
 立即注册
查看: 2379|回复: 2

求助大神,创建链表就是不成功,虽然可以运行。QAQ

[复制链接]
发表于 2019-8-20 13:13:47 | 显示全部楼层 |阅读模式

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

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

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

struct test{
        int data;
        struct test *next;
};
void Creatlist(struct test *head, int a[], int n);
void Printelem(struct test *head);
void Free(struct test *head);
int main()
{
        struct test *head;
        int i = 0,j=1;
        int a[40];
        for(i;i<40;i++,j+=3)
        {
                a[i]=j;
        }
        Creatlist(head,a,10);

        Printelem(head);
        Free(head);
       
}

void Creatlist(struct test *head, int a[], int n)
{
        struct test *p,*s;
        int i;
        head = (struct test*)malloc(sizeof(struct test));
        head->next = NULL;
        head->data = n;
        p = head;
        for(i=0;i<n;i++){
                s = (struct test*)malloc(sizeof(struct test));
                s->data = a[i];
                p->next = s;
                p = p->next;
                printf("%d\n",p->data);
               
               
        }
        p->next = NULL;
        printf("创建完成\n");
       
       
}

void Printelem(struct test *head)
{
        struct test *p = head;
       

        int j = 1;
        while(p!=NULL){
               
       
                printf("%d\t%d\n", j, p->data);
                p = p->next;
                j++;
        }
        printf("输出完成;\n");
}
void Free(struct test *head)
{
        struct test *p = NULL, *ps;
        ps = head;
        while(ps){
       
       
                p = ps;
                ps = head->next;
                free(p);
        }
        printf("释放完成\n");
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-8-20 13:52:15 | 显示全部楼层
如果参数作为输出参数想返回一个地址,参数就要是一个二级指针,void Creatlist(struct test **head, int a[], int n),使用的时候给head的地址Creatlist(&head,a,10);  函数中这样  *head = (struct test*)malloc(sizeof(struct test));
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-8-20 16:36:31 | 显示全部楼层
修改了一下,可以正常运行。
1. 声明部分  struct test *Creatlist(struct test *head, int a[], int n);
2. 主函数里  head = Creatlist(head,a,10);
3. CreateList()函数部分  函数类型为  struct test *Creatlist(struct test *head, int a[], int n),结尾 return head;
4. Free()函数部分 只需要一个指针 struct test *ps = head;
                                                  while( head ){
                                                       ps = head->next;
                                                       free(head);
                                                       head = ps;
                                                  }
5. 望采纳。。。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-10-4 05:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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