#include<stdio.h>
#include<stdlib.h>
struct node{//建造一个结构体 叫做node
int data;//里面有数据域和next域,next的作用是指向下一个节点,next域里有下一个节点的指针地址
struct node *next;
};
int main(){
struct node *next,*q,*p,*head,*t;
int i,n,a;
scanf("%d",&n);
head=NULL;//先将头指针设为空先,后面要用
for(i=0;i<n;i++){
p=(struct node*)malloc(sizeof(struct node));//sizeof(struct node)是求这个结构体的字节数大小,前面那个是强制转化类型 malloc是英文 memery allocate的缩写,意思是内存分配
scanf("%d",&a);
p->data=a;//注意p,q都是指针,->则是一个运算符,意思是进入指针所在的节点(结构体)
//这里的意思就是进入p所在节点的data域,将a赋值到data域里面
p->next=NULL;
if(head==NULL){
head=p;//如果p是第一个节点的话,就把head指针指向p,后面输出就是依靠这个head指针从头遍历输出;
q=p;//这里q是p的前一个节点的指针,没有前节点就要指到一起,后面创新节点,p就在后面,q就在前面
}else q->next=p;q=p;//依靠q指针的移动来链接新节点
}
t=head;
while (t!=NULL){
printf("%d ",t->data);
t=t->next;
}
getchar();
getchar();
free(p);//malloc的内存是“借”的,内存就像手机的后台,是有限的,用完赶紧删了
return 0;
}
纯净版:
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
int main(){
struct node *next,*q,*p,*head,*t;
int i,n,a;
scanf("%d",&n);
head=NULL;
for(i=0;i<n;i++){
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&a);
p->data=a;
p->next=NULL;
if(head==NULL){
head=p;
q=p;
}else q->next=p;q=p;
}
t=head;
while (t!=NULL){
printf("%d ",t->data);
t=t->next;
}
getchar();
getchar();
free(p);
return 0;
}