静态链表
#include <stdio.h>
struct stu{
long num;
float score;
struct stu *next;
};
int main()
{
struct stu a,b,c,*head;
a.num = 1;
a.score = 88.5;
b.num = 2;
b.score = 99;
c.num = 3;
c.score = 89;
head = &a;
a.next = &b;
b.next = &c;
c.next = NULL;
struct stu *p;
p = head;
while(p!=NULL){
printf("%d:%.1f\n",p->num,p->score);
p=p->next;
}
return 0;
}
动态链表
#include <stdio.h>
struct stu{
long num;
float score;
struct stu *next;
};
int n = 0;
//赋值函数,返回指向链表头的指针
struct stu *create(void)
{
struct stu *head;
struct stu *p1,*p2;
head = NULL;
//开辟一个新单元,并让p1、p2指向它
p1=p2=(struct stu *)malloc(sizeof(struct stu));
scanf("%d %f",&p1->num,&p1->score);
while(p1->num != 0){ //以0结束
n++;
if(n==1) head=p1; // head指向第一个节点
else p2->next=p1; // p1所指节点连接到表尾
p2=p1; // p2指向表尾
p1=(struct stu *)malloc(sizeof(struct stu));
scanf("%d %f",&p1->num,&p1->score);
}
p2->next=NULL;
return head;
}
//打印链表
void print(struct stu *head)
{
struct stu *p;
printf("These %d records are:\n",n);
p=head;
while(p!=NULL){
printf("%d %5.1f\n",p->num,p->score);
p=p->next;
}
}
int main()
{
struct stu *p;
p=create();
print(p);
return 0;
}
由于num唯一,我们可以稍作修改建立如下的cmap:
#include <stdio.h>
struct cmap{
long key;
float value;
struct cmap *next;
};
int n = 0;
//map赋值
void cmap_init(struct cmap **head){ //修改的*head需要传入指针**
struct cmap *p1,*p2;
*head = NULL;
//开辟一个新单元,并让p1、p2指向它
p1=p2=(struct cmap *)malloc(sizeof(struct cmap));
scanf("%d %f",&p1->key,&p1->value);
while(p1->key != 0){ //以0结束
n++;
if(n==1) *head=p1; // head指向第一个节点
else p2->next=p1; // p1所指节点连接到表尾
p2=p1; // p2指向表尾
p1=(struct cmap *)malloc(sizeof(struct cmap));
scanf("%d %f",&p1->key,&p1->value);
}
p2->next=NULL;
}
//map打印
void cmap_print(struct cmap *p)
{
printf("These %d records are:\n",n);
while(p!=NULL){
printf("%d %5.1f\n",p->key,p->value);
p=p->next;
}
}
//map查找
int find=0;
void cmap_search(struct cmap *p,long num,float* score){ //修改的score值需要传入指针*
while(p!=NULL){
if(p->key==num){
*score=p->value;
find=1;
}
p=p->next;
}
}
int main()
{
long num=2;
float score=0;
int ret;
struct cmap *p;
cmap_init(&p);
cmap_print(p);
cmap_search(p,num,&score);
if(0 == find){
printf(">> no result!\n");
}else{
printf("%d>>%f\n",num,score);
}
return 0;
}