用C语言做一个链表出现错误0xC0000005: Access Violation. 50
原码#include<stdio.h>#include<stdlib.h>structlist{structlist*next;intnum;};structlist*c...
原码
#include<stdio.h>
#include<stdlib.h>
struct list
{
struct list *next;
int num;
};
struct list* creat(struct list *head,int n);
void print(struct list *head);
main()
{
struct list *head1;
struct list *head2;
int n;
scanf("%d",&n);
head1=creat(head1,n);
print(head1);
return 0;
}
struct list* creat(struct list *head,int n)
{
int i;
struct list *p1,*p2;
head=p1;
for(i=0;i<n;i++)
{
p1=p2=(struct list*)malloc(sizeof(struct list));
scanf("%d",&p1->num);
p2=p1;
if(i==n-1)
p1->next=NULL;
else
p1=p2->next;
}
return head;
}
void print(struct list *head)
{
struct list *temp;
temp=head;
while(temp!=NULL)
{
printf("%6d",temp->num);
temp=temp->next;
}
}
错误提示在倒数第三行
First-chance exception in list.exe: 0xC0000005: Access Violation. 展开
#include<stdio.h>
#include<stdlib.h>
struct list
{
struct list *next;
int num;
};
struct list* creat(struct list *head,int n);
void print(struct list *head);
main()
{
struct list *head1;
struct list *head2;
int n;
scanf("%d",&n);
head1=creat(head1,n);
print(head1);
return 0;
}
struct list* creat(struct list *head,int n)
{
int i;
struct list *p1,*p2;
head=p1;
for(i=0;i<n;i++)
{
p1=p2=(struct list*)malloc(sizeof(struct list));
scanf("%d",&p1->num);
p2=p1;
if(i==n-1)
p1->next=NULL;
else
p1=p2->next;
}
return head;
}
void print(struct list *head)
{
struct list *temp;
temp=head;
while(temp!=NULL)
{
printf("%6d",temp->num);
temp=temp->next;
}
}
错误提示在倒数第三行
First-chance exception in list.exe: 0xC0000005: Access Violation. 展开
1个回答
展开全部
struct list* creat(struct list *head,int n)
{
int i;
struct list *p1,*p2;
head=p1;
for(i=0;i<n;i++)
{
p1=p2=(struct list*)malloc(sizeof(struct list));
scanf("%d",&p1->num);
p2=p1;
if(i==n-1)
p1->next=NULL;
else
p1=p2->next; //p1永远等于郑吵尘p2,这不是永远自己指向自己吗?
}
return head;
}
修改如下
struct list* creat(struct list *head,int n)
{
int i;
struct list *p1,*p2=NULL;
//head=p1; //这句话完全没用
for(i=0;i<n;i++)
{
p1=(struct list*)malloc(sizeof(struct list));
scanf("%d",&p1->num);
p1->next=NULL; //初始化节点
if(p2==NULL) //头结点
{
head=p1; //head为头结点
p2=p1; //p2为最后一个节点
碰型 }
else
{
p2->next = p1; //先申请的节点挂在最后一个节点后面
喊禅 p2=p1; //p2永远为最后一个节点
}
}
return head; //返回头结点
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询