回复 12楼 蚕头燕尾
数据结构(C语言版) 严蔚敏 清华大学出版社
我节选跟这个函数有关的代码吧 其他无关的我就不弄上来了
-------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int Status;
typedef int ElemType;
typedef struct{
ElemType *elem;
int length;
int listsize;
}SqList;
Status InitList(SqList &L)
{
//线性表初始化
L.elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if (!L.elem) exit(OVERFLOW);
L.length=0;
L.listsize=LIST_INIT_SIZE;
return OK;
}//InitList
Status compare(ElemType e1,ElemType e2)
{
if (e1==e2)
return 0;
if ( e1<e2 )
return -1;
return 1;
}
Status LocateElem(SqList L,ElemType e,Status (*compare)(ElemType,ElemType) )
{
int i=1;
while( i<=L.length && (*compare)(L.elem[i-1],e) )
i++;
if(i<=L.length)
return i;
return 0;
}
Status Locate(SqList L,ElemType e)
{
int i=1;
while( i<=L.length && compare(L.elem[i-1],e) )
i++;
if(i<=L.length)
return i;
return 0;
}
Status ListInsert(SqList &L,int i,ElemType e)
{
//线性表已存在 1<i<L.length
//在第i个数据元素之前插入e,后续数据元素后移,L.length加1
ElemType *p;
ElemType *q;
ElemType *newbase;
if (i<1 || i>L.length+1)
return ERROR;
if(L.length>=L.listsize)
{
newbase=(ElemType *)realloc(L.elem,(LIST_INIT_SIZE+LISTINCREMENT)*sizeof(ElemType));
if(!newbase) exit (OVERFLOW);
L.elem=newbase;
L.listsize+=LISTINCREMENT;
}
q=&(L.elem[i-1]);
for( p=&(L.elem[L.length-1]);p>=q;p-- )
{
*(p+1)=*p;
}
*q=e;
L.length++;
return OK;
}//ListInsert
Status ShowList(SqList L)
{
for(int i=0;i<L.length;i++)
printf("L.elem[%d]=%d ",i,L.elem[i]);
printf("\n");
return OK;
}//ShowList
int main(void)
{
ElemType e=3;
SqList L;
InitList(L);
ListInsert(L,1,2);
ListInsert(L,1,3);
ListInsert(L,2,1);
ShowList(L);
if( LocateElem(L,e,(*compare)()) )
printf("线性表中存在数据元素e=%d\n",e);
else
printf("线性表中不存在数据元素e=%d\n",e);
return 0;
}