零基础入门学习C语言011讲:结构体与共用体(4)链表

版权声明:转载请标明出处 https://blog.csdn.net/qq_41556318/article/details/89761680

链 表

什么是链表?

链表是一种常见的重要的数据结构,是动态地进行存储分配的一种结构。

链表的组成:

头指针:存放一个地址,该地址指向第一个元素

结点:用户需要的实际数据和链接节点的指针

我们尝试根据下图建立链表:

#include <stdio.h>

struct student
{
	long num;
	float score;
	struct student *next;
};

void main()
{
	struct student a, b, c, *head;

	a.num = 10101;
	a.score = 89.5;
	b.num = 10103;
	b.score = 90;
	c.num = 10107;
	c.score = 85;

	head = &a;
	a.next = &b;
	b.next = &c;
	c.next = NULL;

	do
	{
		printf("%ld %5.1f\n", head->num, head->score);
		head = head->next;
	} while (head != NULL);
}

建立动态链表

所谓建立动态链表是指在程序执行过程中从无到有地建立起一个链表,即一个一个地开辟结点和输入各结点数据,并建立起前后相链的关系。

作业:根据下面的分析写一程序建立一个含有学生(学号,成绩)数据的单向动态链表。

(约定:我们约定学号不会为零,如果输入的学号为0,则表示建立链表的过程完成,该结点不应连接到链表中。)

我们将以图文并茂的方式来展示链表的具体创建过程!!

我们约定学号不会为零,如果输入的学号为0,则表示建立链表的过程完成,该结点不应连接到链表中。

如果输入的p1->num不等于0,则输入的是第一个结点数据(n=1),令head=p1,即把p1的值赋给head,也就是使head也指向新开辟的结点p1所指向的新开辟的结点就成为链表中第一个结点。

再开辟一个结点并使p1指向它,并输入该结点的数据。

实现链表输出

源代码如下:

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

#define LEN sizeof(struct student)

struct student *creat();   //创建链表
void print(struct student *head);   //打印链表

struct student
{
	int num;
	float score;
	struct student *next;
};

int n; //全局变量,用来记录存放了多少数据。

void main()
{
	struct student *stu;

	stu = creat();
	print(stu);

	printf("\n\n");
	system("pause");
}

struct student *creat()
{
	struct student *head;
	struct student *p1, *p2;

	p1 = p2 = (struct student *)malloc(LEN);

	printf("Please enter the num :");
	scanf("%d", &p1->num);
	printf("Please enter the score :");
	scanf("%f", &p1->score);

	head = NULL;
	n = 0;

	while (p1->num)
	{
		n++;
		if (1 == n)
		{
			head = p1;
		}
		else
		{
			p2->next = p1;
		}

		p2 = p1;
		p1 = (struct student *)malloc(LEN);

		printf("\nPlease enter the num :");
		scanf("%d", &p1->num);
		printf("Please enter the score :");
		scanf("%f", &p1->score);
	}

	p2->next = NULL;

	return head;
}

void print(struct student *head)
{
	struct student *p;
	printf("\nThere are %d records!\n\n", n);

	p = head;
	if (head)
	{
		do
		{
			printf("学号为 %d 的成绩是: %f\n", p->num, p->score);
			p = p->next;
		} while (p);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41556318/article/details/89761680