链表—C语言链表中数据域是结构体该如何操作

链表是数据结构中的首先接触到的,常规的链表数据域为int型,如果链表中数据域是一个结构体该如何操作呢?
首先看一个例子:
定义一个学生结构体,然后用单向链表保存学生信息,由scanf输入学生信息后形成链表,再打印出所有学生信息
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct
{
          
   
	char name[20];
	int age;
	int score;
}student;	//定义了一个学生信息的结构体
typedef struct node_t
{
          
   
	student data;
	struct node_t *next;
}Node;	//定义了一个链表节点
Node *init()
{
          
   
	Node *head=malloc(sizeof(struct node_t));
	head->next=NULL;
	return head;
}	//链表初始化
void insert(Node *head,int age,int score,char *name)
{
          
   
	Node *p=malloc(sizeof(struct node_t));
	Node *q=head;
	while(q->next!=NULL)
		q=q->next;
	q->next=p;
	strcpy(p->data.name,name);	//这里需要字符串的传递,需要使用strcpy()函数,函数的参数需要两个指针,
								//这里是p->data.name(同下行注释name为结构体中数组的首地址)和name(主函数中name的首地址)
	p->data.age=age;	//p作为节点的地址->节点中的data,data作为结构体变量名需要.上data结构体中的变量
	p->data.score=score;
	p->next=NULL;
}	//链表插入函数
int main()
{
          
   
	Node *head=init();
	int l,i,age,score;
	char name[20];
	printf("input lenght of list: ");
	scanf("%d",&l);
	for(i=0;i<l;i++)	//循环输入链表的信息
	{
          
   
		printf("input age of node: ");
		scanf("%d",&age);
		printf("input score of node: ");
		scanf("%d",&score);
		printf("input name of node: ");
		scanf("%s",name);
		insert(head,age,score,name);	//将信息插入到链表中
	}
	Node *p=head;
	while(p->next!=NULL)	//输出链表的信息
	{
          
   
		p=p->next;
		printf("%-3d",p->data.age);
		printf("%-3d",p->data.score);
		printf("%s
",p->data.name);
	}
	return 0;
}
经验分享 程序员 微信小程序 职场和发展