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

猜你喜欢

转载自blog.csdn.net/chendongpu/article/details/121489500
今日推荐