构造C链表
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
int main(){
int n,a;
struct node* head = NULL;
struct node *pre;
struct node *p;
scanf("%d",&n);
for(int i =0;i<n;i++){
scanf("%d",&a);
p = (struct node*)malloc(sizeof(struct node)); //申请一块内存
p->data = a;
p->next = NULL; //链表无后继指针
if(head == NULL){ //如果head没有赋值 则这个为第一个元素
head = p;
}
else{
pre->next = p;//否则上一个元素的后继为这个元素
}
pre = p; //这个元素变为上个元素,为下一个输入做准备
}
struct node*now = head;//遍历链表
while(now != NULL){
printf("%d\n",now->data);
now = now->next;
}
return 0;
}

浙公网安备 33010602011771号