//逆向建立链表 ,相当于一个不断头插结点的过程,因为每次头插,
//数组中的元素相当于每次都要被插入到前面,因此要逆向遍历数组存值
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next;
}ElemSN;
ElemSN *Createlink(int *a,int n)
{
ElemSN *head=NULL,*np;
for(int i=n-1;i>=0;i--)
{//逆向跑数组,头插数组元素
np=(ElemSN *)malloc(sizeof(ElemSN));
np->data=*(a+i);
np->next=head;//头插
head=np;//头结点前移
}
return head;
}
void Printlink(ElemSN *head)
{
ElemSN *p;
for(p=head;p;p=p->next)
{
printf("%d",p->data);
}
}
int main()
{
int n;
int *a;
printf("请输入数组长度:");
//动态分配数组
scanf("%d",&n);
a=(int *)malloc(n*sizeof(int));
for(int i=0;i<n;i++)
{
scanf("%d",a+i);
}
ElemSN *head=NULL;
//创建链表
head=Createlink(a,n);
//输出链表
Printlink(head);
return 0;
}