哈哈哈,今天有点标题党。
不过,我会争取让您搞懂的,一起加油吧!!ヾ(◍°∇°◍)ノ゙ヾ(◍°∇°◍)ノ゙
引言:在开始创建链表之前,不妨先了解一下,链表的出现是为了什么?什么时候用数组,什么时候用链表呢?
回答这两个问题,只需要一个对比就可以完成:
数组 | 优点:可以进行随机访问 缺点:插入或者删除数据极不方便 |
链表 | 优点:插入或者删除数据方便 缺点:需要“顺藤摸瓜”地访问 |
了解链表的的用处后,现在让我们步入正题:
链表的创建有两种方式:1.静态链表 2.动态链表
1.静态链表的创建
输入:暂无。
输出:三名学生的学号,姓名,成绩。
#include <stdio.h>
#include <string.h>
struct student//定义学生这个结构体
{
long num;
char name[100];
float g;
struct student *next;
};
int main()
{
struct student a,b,c,*p,*head;
a.num=10000;//对结构体中的成员进行赋值
strcpy(a.name,"aa");
a.g=99.0;
b.num=10001;
strcpy(b.name,"bb");
b.g=99.0;
c.num=10002;
strcpy(c.name,"cc");
c.g=99.0;
head=&a;// 头指针指向节点a;
a.next=&b;
b.next=&c;
c.next=NULL;
p=head;
printf("学号 姓名 成绩");
printf("\n");
do{
printf("%ld,%s,%f",p->num,p->name,p->g);
printf("\n");
p=p->next;//重点!!p的作用:head只能够指向a节点,而p像head的小弟,源源不断的往后指,才能一个个输出
}while(p!=NULL);
return 0;
}
图解:(画的很粗糙(。・_・。)ノI’m sorry~)
结果:
重点!!p的作用:head只能够指向a节点,而p像head的小弟,源源不断的往后指,才能一个个输出 。
2.动态列表的创建(只是静态的进阶版)
输入:三名学生的学号,姓名,成绩。
输出:三名学生的学号,姓名,成绩。
#include <stdio.h>
#include <stdlib.h>//使用malloc函数
#define NULL 0
#include<stdbool.h>//while的判断中用到了布尔变量
#include <string.h>//用到了strcmp
typedef struct student//学到的新东西,对结构体重命名为"stu" (typedef称为类型定义)
{
long num;
char name[100];
float g;
struct student *next;
}stu;
stu *create()//返回指针的函数
{
int n=0;
stu* head,*p1,*p2;
char name[100];
while(true)
{
gets(name);
if(strcmp(name,"0")==0)//如果学生的名字为0,则直接退出函数
{
return head;
}
p1=(stu*)malloc(sizeof(stu));
//让p指向申请一个新的节点,存储与堆区
if (p1 == NULL)
{
exit(0);//若申请失败,退出整个程序
}
strcpy(p1->name,name);
scanf("%ld%f",p1->num,p2->g);
p1->next=NULL;
if(head==NULL)
{
head=p1;
}
else{
p2->next=p1;//该算法看图
}
p2=p1;
n++;//看有几个学生
return head;
}
}
int main()
{
stu *head,*p1,*p2,*p;
p=head;
head=create();
do{
printf("%ld %s %f",p1->num,p1->name,p1->g);//输出节点值
p=p->next;//指针指向下一节点
}while(1);//想要输出整个链表,只需要知道头指针就可以了
return 0;
}
图解:(画的很粗糙(。・_・。)ノI’m sorry~)
这只是尾部插入法,还有一个头部插入不想搞了,好困,得睡了
谢谢看我文章的朋友,祝你也好梦哟,拜拜!!