C语言链表的建立

来源:百度知道 编辑:UC知道 时间:2024/06/07 18:24:31
建立并输出一个含有n过 数据的链表
我写的代码
#include<stdio.h>
#include<malloc.h>
#define NULL 0
struct list
{
int data;
struct list *next;
};
int m;
struct list *creat_n()
{
int n;
struct list *p1,*p2;
struct list *head;
m=0;
scanf("%d",&n);
p1=p2=(struct list*)malloc(sizeof(struct list));
scanf("%d",&p1->data);
head=NULL;
for(int i=1;i<n;i++)
{
m=m+1;
if(m==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct list *)malloc(sizeof(struct list));
scanf("%d",&p1->data);
}
p2->next=NULL;
return(head);
}
void print(struct list *head)
{
struct list *p;
printf("%d\n",m);
p=head;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
void main()
{
struct list *head,*q;
int data;
head=creat_n()

在创建函数中的
for(int i=1;i<n;i++)
{
m=m+1;
if(m==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct list *)malloc(sizeof(struct list));
scanf("%d",&p1->data);
}
p2->next=NULL;
把这句p2->next=NULL; 改为p2->next= p1;p1->next= NULL;
你的程序输不出来最后一个是因为最后的元素没有加入链表。

for(int i=1;i<n;i++)//怎么从1开始?
//这样不是输少了一个进去?

0