静态链表:所有的节点都是在程序中定义的,不是临时开辟的,也不能用完后释放,这种链表成为静态链表。
typedef struct student
{
int id;
char name[30];
struct student* next;
}STU;
void chainprint(STU stu)
{
STU* pstu = &stu;
while (pstu)
{
printf("%3d,%15s\n", pstu->id, pstu->name);
pstu = pstu->next;
}
}
int main()
{
STU s1 = { 1,"liming" ,NULL};
STU s2 = { 2,"zhangxiao" ,NULL};
STU s3 = { 3,"wangda" ,NULL};
STU s4 = { 4,"zhaosi",NULL };
s1.next = &s2;s2.next = &s3;
s3.next = &s4;
chainprint(s1);
system("pause");
return 0;
动态链表:在程序执行过程中从无到有地建立起一个链表,即一个一个地开辟节点和输入各节点数据,并建立起前后相互链接的关系。
typedef struct student
{
int id;
char name[30];
struct student* next;
}STU;
void chainprint(STU stu)
{
STU* pstu = &stu;
while (pstu)
{
printf("%3d,%15s\n", pstu->id, pstu->name);
pstu = pstu->next;
}
}
void freechain(STU stu)
{
STU* pstu = &stu;
STU* tmp;
while (pstu)
{
tmp = pstu->next;
free(pstu);
pstu = tmp;
}
}
int main()
{
STU* s1 =(STU*)malloc(sizeof(STU));
STU* s2 =(STU*)malloc(sizeof(STU));
STU* s3 =(STU*)malloc(sizeof(STU));
STU* s4 =(STU*)malloc(sizeof(STU));
s1->id = 1;s2->id = 2;
s3->id = 3;s4->id = 4;
strcpy(s1->name, "aaaa");strcpy(s2->name, "bbbb");
strcpy(s3->name, "cccc");strcpy(s4->name, "dddd");
s1->next = s2;s2->next = s3;s3->next = s4;s4->next = NULL;
chainprint(*s1);
system("pause");
return 0;
}