C语言链表的创建

基本结构组成:指针;结构体。

struct link{
    int num;//数据域
    struct link *next;//指针域
};

需要进行的操作:内存动态管理

分配内存空间函数malloc:

void *malloc(unsigned int size);功能是在内存的动态存储区中分配一块长度为size的连续区域。如果分配成功,返回值为该区域的首地址。

首先创建链表需要1.读取数据;2.生成新节点;3.将数据存入新节点;4.将新节点插入链表中

#include<stdio.h>
#include<malloc.h>//引用malloc的库文件
#define N 10
typedef struct link{
    int data;
    struct link *next;//注意定义指针的标识符
}SLIST;
SLIST *creatlist(int *a)
{ 
 SLIST *h,*p,*q; 
 int i;
h=p=(SLIST *)malloc(sizeof(SLIST));
for(i=0; i<N; i++)
{ q=(SLIST *)malloc(sizeof(SLIST));
q->data=a[i]; p->next=q; p=q;
}
p->next=0;
return h;
}
void outlist(SLIST *h)
{ SLIST *p;
p=h->next;
if (p==NULL) printf("\nThe list is NULL!\n");
else
{ printf("\nHead");
do { printf("->%d",p->data); p=p->next; } while(p!=NULL);
printf("->End\n");
}
}
int main(){
    int a[10]={1,2,3,4,5,6,7,8,9,10};
    SLIST *head;
    head=creatlist(a);
    outlist(head);
}


未完成等待完成

Q.E.D.