今天學習了思成老師的數據結構實戰教程 寫了一個順序表 插入和刪除的操作 把源碼共享給大家 一共包括list.c stu.h main.c list.h ? .h文件是頭文件 需要引入 具體的功能我都已經在代碼中寫明了
list.h代碼如下:
//線性表的定義在頭文件中實現
#ifndef _LIST_H
#define _LIST_H
#define _LIST_INIT_SIZE 10
#define _LIST_INCREME 10
typedef struct
{
ElemType * elem;//首地址
int length;
int size;
}LIST;
LIST *InitList();
void FreeList(LIST *l);
int InsertList(LIST *l,int i,ElemType *e);
int DeleteList(LIST *l,int i);
#endif
list.c代碼如下
#include
#include
#include "stu.h"
#include "list.h"
//線性表的初始化,此時數據存儲的大小的內存還未開辟 開辟的是list.h的大小
LIST *InitList()
{
LIST *l=(LIST *)malloc(sizeof(LIST));
//判斷開辟是否成功
if(l==NULL)
exit(0);
//開辟存儲數據的內存的區域
l->elem=(ElemType *)malloc(_LIST_INIT_SIZE *sizeof(ElemType));
//如果開辟成功的話就釋放掉內存
if(l->elem==NULL)
{
free(l);
exit(0);
}
//有效長度賦初值為0
l->length=0;
l->size=_LIST_INIT_SIZE;
return l;
}
//釋放對區內存的函數
void FreeList(LIST *l)
{
//要先釋放成員的空間
free(l->elem);
free(l);
}
//第一個參數要傳得是插入哪一個線性表中去 i指位置
int InsertList(LIST *l,int i,ElemType *e)
{
//定義一些指針 指向相應的位置
ElemType *p=NULL,*q=NULL,*newElem=NULL;
if(l==NULL || e==NULL)
return 0;
//i指的是第幾個位置 不是下標
if(i<1||i>l->length+1)
return 0;
//if有效長度大于最大的長度的時候 重新開辟一塊內存
if(l->length>=l->size)
{
newElem=realloc(l->elem,(l->size+_LIST_INCREME)*sizeof(ElemType));
if(newElem==NULL)
return 0;
l->elem=newElem;
l->size+=_LIST_INCREME;
}
//q指向插入的位置 i-1代表下標
q=&l->elem[i-1];
//指向最后一個有效的數據元素
for(p=&(l->elem[l->length-1]);p>=q;p--)
*(p+1)=*p;
*q=*e;
++l->length;
return 1;
}
int DeleteList(LIST *l,int i)
{
ElemType *p=NULL,*q=NULL;
if(l=NULL)
return 0;
if(i<1|| i>l->length)
return 0;
p=&l->elem[i-1];
q=&l->elem[l->length-1];
for(;p
*p=*(p+1);
--l->length;
return 1;
}
stu.h代碼如下
#ifndef _STU_H
#define _STU_H
//定義一個學生的結構體
typedef struct
{
char sno[4];
char name[21];
char sex[3];
int score;
}ElemType;
#endif
main.c代碼如下
#include
#include "stu.h"
#include "list.h"
ElemType stu[3]={
{"S101","張三","男",80},
{"S102","小紅","女",75},
{"S103","王五","男",90},
};
void main()
{
int i;
LIST *list=NULL;
//通過函數初始化空間
list=InitList();
for(i=0;i<3;i++)
InsertList(list,1,&stu[i]);
DeleteList(list,2);
FreeList(list);
}