栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言实现线性链表

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 
#include 
#include 



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 
#include 
#include 
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("%st%st%st%dn",p->sno,p->name,p->sex,p->score);		
		p++;
	}
	return 0;
}

输出

S03     小红    女      80
S02     王五    男      90
S01     张三    男      100
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/588794.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号