C程序设计--结构体+单向链表

链表

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. … …等等

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值