C语言实现数组转换单链表
//数组转换为单链表
#include <>
#include <>
// 创建结构体
struct list{
int data;
struct list *next;
};
int main() {
//创建数组
int a[] = {1,2,3,4,5,6,7,8,9};
//数组长度
int l = sizeof(a)/sizeof(a[0]);
//创建p指针存放p节点的地址
struct list *p = NULL;
//创建head指针
struct list *head = NULL;
//链表为空,创建头节点,申请内存空间
head = malloc(sizeof(struct list));
//创建end指针,指向上一结束节点
struct list *end = head;
for (int i=0;i<l;i++){
//新建p节点
p = malloc(sizeof(struct list));
//指针访问内部成员
p->data = a[i];
//上一节点的尾指针指向新节点
end->next = p;
//新增节点变为尾节点
end = p;
}
//末尾节点指针变为空
end->next = NULL;
//从头节点的下一节点开始打印
struct list *x = head->next;
for (int i=0;i<l;i++){
printf("%d->",x->data);
x = x->next;
}
}