阿龙写的代码并注释的,学习了。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node*next; //链表函数用结构体类型来做,就像数组用int型
};
struct node*creat(int n)
{
int i;
struct node*head,*p,*tail;
head=(struct node*)malloc(sizeof(struct node)); //head只是一个头,但是也给他开辟物理空间
head->next=NULL;
tail=head; //tail只是一个变量,它来确定链表所处的位置,就像数组中的int型的下表变量i
for(i=0;i<n;i++)
{
p=(struct node*)malloc(sizeof(struct node)); //链表与数组的不同:数组现统一开辟空间再存,链表开一个存一个。
scanf("%d",&p->data); //输入数据
p->next=NULL; //把每次输入的新数据一个放到链表的最后面
tail->next=p; //通过tail来进行连接,tail起到改变下标的作用,他不占内存
tail=p; //改变tail与p的位置来改变链子的尾部,经行曾加元素
}
return head; //返回一个结构体类型的返回值
}
void list(struct node*l)
{
struct node *r;
r=l;
while(r->next->next!=NULL) //为了跳过最后一个,这样最后就不会输出空格了
{
printf("%d ",r->next->data);
r=r->next;
}
printf("%d\n",r->next->data);
}
int main()
{
int n;
scanf("%d",&n);
list(creat(n));
return 0;
}