C语言链表又出问题了!!

2025-03-12 03:07:13
推荐回答(2个)
回答1:

#include 
#include 
#include 
#include 
struct dept {
   int id;
   char *name;
   int balance;
   struct dept *next;
};
typedef struct dept dept_t;

dept_t *create_dept(int dept_id, char *dept_name, int dept_balance)
{
 dept_t *list_head,*newNode,*tailNode;
 list_head =tailNode= (dept_t *)malloc(sizeof(dept_t));//创建空链表
 tailNode->next=NULL;
 newNode= (dept_t *)malloc(sizeof(dept_t));//创建第一个节点
 newNode->id = dept_id;
 newNode->name = dept_name;
 newNode->balance = dept_balance;
 newNode->next = NULL;
 tailNode->next=newNode;
 tailNode=newNode;
 return list_head;//你在这里没返回

}

void free_dept(dept_t *dept)
{   
 dept_t * temp;
dept_t *cur=dept->next;

   while(cur!= NULL)//这里是判断链表节点存不存在,是不管里面的值的,
   {                       //只能用地址,如果用*cur,它指向的是一个结构体数据,会报错.
 temp=cur->next;
      free(cur);
 cur=temp;
   }
   dept->next = NULL;
}

int main()

    int sum;
    char *a;
    dept_t *p;
    scanf("%s %d",a,&sum);
    p=create_dept(51423, a, sum);//这里多了*,指针变量存的是地址
    free_dept(p);
}

//***修改成这样就OK了

回答2:

问题太多,复杂