我不知道是我代码写错了还是怎么
麻烦各位大家看看
//单链表前插法
#include<stdio.h>
#include<stdlib.h>
struct Student
{
int num;
struct Student *next;
};
struct Student *create()
{
struct Student *head,*n;//n是新节点
int i;
head=(struct Student *)malloc(sizeof(struct Student));
head->next=NULL;//头指针指向为空
while(n->num!=0)
{
n =(struct Student *)malloc(sizeof(struct Student));
printf("num=");
scanf("%d",&n->num);
n->next=head->next;//新节点指向head节点指向的节点
head->next=n;
}
// free(n);//添加free输出不正确
return head;
}
void print(struct Student *head)
{
int s;
struct Student *temp;
printf("-----------the list -----------");
temp=head;
while(temp!=NULL)
{
printf("the num=%d\n",temp->num);
temp=temp->next;
}
}
int main(){
struct Student *head;//定义一个头指针
head=create();
print(head);
return 0;
}
不加free
链表用的就是这个指针,你不应该在插入的时候free的才是对的,但是你应该free是在链表删除一个节点或者删除的时候依次free掉这里的内存。
你得代码能过? 第一次用while的时候 你的n没有初始化啊,这指针指向。。。
你先把这个没初始化改了,然后看有问题吧,可能是这里导致的,没初始化的话,内存是乱的。
至于创建的逻辑 看起来没问题,至少我没看出问题
修改见注释处,供参考:
//单链表前插法
#include<stdio.h>
#include<stdlib.h>
struct Student
{
int num;
struct Student *next;
};
struct Student *create()
{
struct Student *head,*n;//n是新节点
int i;
head=(struct Student *)malloc(sizeof(struct Student));
head->next=NULL;//头指针指向为空
while(1) //while(n->num!=0) 修改
{
n =(struct Student *)malloc(sizeof(struct Student));
if (!n) break;
n->next = NULL;
printf("num=");
scanf("%d",&n->num);
if (n->num == 0){ // 修改
free(n); //free 添加在这里,如果输入 0 则结束输入,释放最后申请的空间
n = NULL;
break;
}
n->next=head->next;//新节点指向head节点指向的节点
head->next=n;
}
return head;
}
void print(struct Student *head)
{
int s;
struct Student *temp;
printf("-----------the list -----------\n");//修改
temp=head->next; //temp=head; 修改
while(temp!=NULL)
{
printf("the num=%d\n",temp->num);
temp=temp->next;
}
}
int main(){
struct Student *head;//定义一个头指针
head=create();
print(head);
return 0;
}
//单链表前插法
#include <stdio.h>
#include <stdlib.h>
typedef struct _Student
{
int num;
struct _Student *next;
} Student;
Student *create()
{
Student *head = (Student *)malloc(sizeof(Student));
head->next = NULL;
Student *tail = head;
while (1)
{
int num;
scanf("%d", &num);
if (num == 0)
break;
Student *p = (Student *)malloc(sizeof(Student));
p->num = num;
p->next = NULL;
tail->next = p;
tail = p;
}
return head;
}
void destroy(Student *head)
{
while (head)
{
Student *p = head;
head = head->next;
free(p);
}
}
void print(Student *head)
{
Student *p = head->next;
while (p)
{
printf("%d ", p->num);
p = p->next;
}
}
int main()
{
Student *head = create();
print(head);
destroy(head);
return 0;
}