C语言实现线性链表

新建一个的头文件stu.h

#ifndef _STU_H
	#define _STU_H
	typedef struct _ElemType{
		char sno[5];
		char name[21];
		char sex[3];
		int score;
	}ElemType;
#endif

新建一个的头文件.h

#ifndef _LIST_H
	#define _LIST_H
	#define LIST_INIT_SIZE 10
	#define LIST_INCREME 10
	typedef struct _LIST{
		ElemType *elem;
		int length;//具体存放的元素长度
		int size;//链表的容量
	}LIST;

	LIST *InitList();
	int InsertList(LIST* List,int i,ElemType* elem);
#endif

新建list.c





#include "stu.h"
#include "list.h"
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>



LIST *InitList()
{
	LIST* List=(LIST*)malloc(sizeof(LIST));
	if(List==NULL){
		exit(0);
	}
	List->elem=(ElemType*)malloc(LIST_INIT_SIZE * sizeof(ElemType));

	if(List->elem==NULL){
		free(List);
		exit(0);
	}

	List->length=0;
	List->size=LIST_INIT_SIZE;
	return List;
}


int InsertList(LIST* List,int i,ElemType* elem)
{
	ElemType* q=NULL,*p=NULL;
	if(List==NULL || elem==NULL)
	{
		return 0;
	}

	if(i<0 || i>LIST_INIT_SIZE)
	{
		if(List->length > List->size)
		{
			List->elem=(ElemType*)realloc(List->elem,(List->size+LIST_INCREME)*sizeof(ElemType));
			List->size+=LIST_INCREME;
		}
	}
	
	if(List->elem==NULL){
		return 0;
	}

	p=&(List->elem[List->length-1]);
	q=&(List->elem[i-1]);
	for(;p>=q;p--){
		*(p+1)=*p;		
	}
	*q=*elem;
	++List->length;
	return 1;	
}

新建入口文件main.c

#include "stu.h"
#include "list.h"
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
ElemType stu[3]={
	{"S01","张三","男",100},
	{"S02","王五","男",90},
	{"S03","小红","女",80}
};

int main()
{
	LIST *List=InitList();
	ElemType *p;
	int i;
	for(i=0;i<3;i++)
	{
		InsertList(List,1,&stu[i]);
	}
	
	p=List->elem;
	for(i=0;i<3;i++)
	{
		printf("%s\t%s\t%s\t%d\n",p->sno,p->name,p->sex,p->score);		
		p++;
	}
	return 0;
}

输出

S03     小红    女      80
S02     王五    男      90
S01     张三    男      100
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

reg183

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值