链表—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\n",p->data.name);
	}
	return 0;
}
作者:conspicuous
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 8
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值