链表
head指向第一个元素,第一个元素又指向第二个元素 … … 直到最后一个元素,该元素不再指向全体元素,它称为“表尾”,它的地址部分放一个“NULL”(表示“空地址”),链表到此结束。
1. 建立一个简单的静态链表:
案例:如上图所示的简单链表,并输出各节点中的数据
代码实现
#include<stdio.h>
struct Student{//声明结构体
int num;
float score;
struct Student *next;
};
int main(){
struct Student a,b,c,*head,*p;
head=&a;
a.num=10101;
a.score=98.5;
a.next=&b;
b.num=10103;
b.score=90;
b.next=&c;
c.num=10107;
c.score=85;
c.next=NULL;
p=head;
do{
printf("%d,%5.1f\n",p->num,p->score);
p=p->next;
}while(p!=NULL);
return 0;
}
运行结果:
代码说明:
上述程序中,所有的结点都是在程序中定义的,不是临时开辟的,也不能用完后释放。这种链表成为“静态链表”。
2. 建立一个动态链表(需要头文件:<stdlib.h>):
案例:建立一个单向链表,并用函数实现 输入、输出 各节点中的数据
代码实现:
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct Student)
struct Student{
long num;
float score;
struct Student *next;
};
int n;//输入的个数,定义为全局变量
struct Student* creat(){//返回一个指向struct Student类型元素的指针,即返回头指针
struct Student *head;
struct Student *p1,*p2;
n=0;
p1=p2=(struct Student *)malloc(LEN);
scanf("%ld %f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0){
n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct Student *)malloc(LEN);
scanf("%ld %f",&p1->num,&p1->score);
}
p2->next=NULL;
return head;
}
void print(struct Student *head){
struct Student *p;
printf("\nNow,Three %d records are:\n",n);
p=head;
if(head!=NULL){
do{
printf("%ld %5.1f\n",p->num,p->score);
p=p->next;
}while(p!=NULL);
}
}
int main(){
struct Student *head;
head=creat();
print(head);
return 0;
}
运行结果:
输入函数:
struct Student* creat(){//返回一个指向struct Student类型元素的指针,即返回头指针
struct Student *head;
struct Student *p1,*p2;
n=0;
p1=p2=(struct Student *)malloc(LEN);
scanf("%ld %f",&p1->num,&p1->score);
head=NULL;
while(p1->num!=0){
n++;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=(struct Student *)malloc(LEN);
scanf("%ld %f",&p1->num,&p1->score);
}
p2->next=NULL;
return head;
}
输出函数:
void print(struct Student *head){
struct Student *p;
printf("\nNow,Three %d records are:\n",n);
p=head;
if(head!=NULL){
do{
printf("%ld %5.1f\n",p->num,p->score);
p=p->next;
}while(p!=NULL);
}
}
注:本博客知识点较为简单。如想了解更多关于链表的知识,建议阅读以下文章
1.https://blog.csdn.net/huangjh2017/article/details/73818062
2.https://www.cnblogs.com/maluning/p/7966875.html
3.https://blog.csdn.net/m_zhurunfeng/article/details/54809821
4. … …等等