文件1 list.c
#include<stdio.h>
#include"list.h"
#include<stdlib.h>
#include<string.h>
/*
函数名 creatList;
功能 创建链表 申请空间
返回值 无
定义一个指针函数返回的就是个函数
*/
LIST *creatList(void)
{
LIST * pList = NULL;
pList = (LIST *)malloc(sizeof(LIST));
//清空 并且初始化
if(NULL == pList){
memset(pList,0,sizeof(LIST));
}
//指针函数 所以要返回pList
return pList;
}
/*
函数名称:destoryList
函数功能 : 销毁线性表
参数:LIST *pList 指向线性表首地址的指针
函数返回值:无
*/
void destoryList(LIST *pList)
{
LIST * pDel = NULL;
if(NULL == pList)
{
return ;
}
while(1)
{
//找到被删除的结点
pDel = pList->pNext;
if(NULL == pDel)
{
break;
}
//保护后面的结点
pList->pNext = pDel->pNext;
free(pDel);
}
free(pList);
pList = NULL;
}
/*
函数名:insertList
功能 给线性表插入数据(前插法)(尾插法)(中间插入)
参数:LIST *pList 指向首地址的指针;
int offset 要插入的位置;
data_type item 要插入的元素
函数返回值 成功时候,返回0;失败的时候返回-1;
*/
int insertList(LIST *pList,int offset,data_type item)
{
LIST *pTmp = NULL; //尾结点要插入的位置
LIST *pNew = NULL; //头结点要插入的数据
//1.判断是否可以插入
if(NULL == pList)
{
return ERR;
}
//2.新建结点 并且赋值
pNew = (LIST *)malloc(sizeof(LIST));
if(NULL == pNew)
{
return ERR;
}
pNew->data = item;
pNew->pNext = NULL;
//从头结点插入
if(HEAD == offset)
{
//找到要插入的位置--pList
//3.保护后面的结点
pNew->pNext = pList->pNext;
//4.链接新的结点
pList->pNext = pNew;
}
//从尾结点插入 准确的说叫接入
if(TAIL == offset)
{
//找到要插入的结点
pTmp = pList;
//3. 保护后面的结点
while(NULL != pTmp->pNext)
{
//向后移动尾结点
pTmp = pTmp->pNext;
}
//4. 接入新的结点
pTmp->pNext = pNew;
}
return OK;
}
/* 函数名称 :showList
函数功能: 打印线性表
函数参数:LIST*pList
*/
void showList(LIST *pList)
{
LIST *pstr = pList;
if(NULL == pList)
{
return ;
}
while(1){
if(NULL != pstr->pNext)
{
printf("%d",pstr->data);
pstr = pstr->pNext;
}else{
break;
}
}
printf("\n\t");
}
文件2 list.h
#ifndef _LIST_H_
#define _LIST_H_
typedef int data_type;
typedef struct list
{
data_type data;
struct list *pNext;
}LIST;
enum result{
ERR = -1,
OK,
FLASE =0,
TRUE,
};
enum offset
{
TAIL=-1,
HEAD,
};
//声明一个指针函数返回的就是creatList
LIST *creatList(void);
//声明一个函数 销毁线性表;
void destoryList(LIST *pList);
// 声明一个插入数据给线性表的函数
int insertList(LIST *pList,int offset,data_type item);
void showList(LIST*pList);
#endif
文件3 test.c
#include<stdio.h>
#include"list.h"
int main(void)
{
LIST*pList;
data_type data;
pList = creatList();
if(NULL == pList)
{
return ERR;
}
insertList(pList,0,52);
insertList(pList,0,32);
insertList(pList,0,22);
insertList(pList,0,12);
showList(pList);
return 0;
}
运行结果如下