#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
//Status 是函数反回类型,其值是函数结果状态代码//
typedef int Status;
//ElemType根根实际需要的类型定义,暂设为int
typedef int ElemType;
#define LIST_INIT_SIZE 100 //线性表存储空间的初始分配量
#define LISTINCREMENT 10 //线性表存储空间的分配增量
typedef struct {
ElemType *elem;
int length;
int listsize;
}SqList;
Status InitList_Sq(SqList &L) {
//构造一个空的顺序线性表L
L.elem = (ElemType *) malloc( LIST_INIT_SIZE * sizeof(ElemType));
if ( !L.elem) exit (OVERFLOW ); //存储空间分配失败
L.length= 0; //空表长度为0
L.listsize = LIST_INIT_SIZE; //初始存储容量
return OK;
}//InitList_Sq
int LocateElem_Sq(SqList L,int e, Status (*compare)(ElemType,ElemType)) {
//在顺序线性表L中查找第1个值与e满足compare()的元素的位序
//若找到,则返回其在L中的位序,否则返回0
int i =1; //i初使值为第一个元素的位序
ElemType *p = L.elem; //p初使值为第一个元素的存储位置
while (i <=L.length && !(*compare)(*p++,e))
++i;
if ( i<= L.length)
printf("所匹配的元素位置在:%d ",i);
printf("\n");
return 0;
}
int compare(ElemType a,ElemType b) {
if (a==b)
return TRUE;
else
return FALSE;
}
Status ListPrint_Sq(SqList &L,int n) {
//输入一个顺序表
int i;
//ElemType *p;
L.length=n;
if (!L.elem)
{
printf( "List is not exit! ");
return ERROR;
}
printf("please input the element:\n");
for(i=0;i<n;i++)
{
scanf("%d",&L.elem[i]);
}
printf("please output the element:\n");
for(i=0;i<n;i++)
{
printf("%d ",L.elem[i]);
}
printf("\n");
return 0;
}
Status ListInsert_Sq(SqList &L, int i,ElemType e) {
//在顺序线性表L中第i个位置之前插入新的元素e, 1 <=i <=ListLength_Sq(L) +1
int j;
int *p,*q;
if (i <1 || i >L.length+1) //判断有关参数的合理性:i值不合法
return ERROR;
if ( L.length >= L.listsize )
{ //存储空间不够需要分配
L.elem = (ElemType*)realloc(L.elem,(L.listsize+LISTINCREMENT) *sizeof(ElemType));
if (!L.elem) exit(OVERFLOW); //空间分配失败
L.listsize +=LISTINCREMENT;
}
q = &L.elem[i-1];//q为插入位置
for (p = & (L.elem[L.length-1]); p>=q; --p)
{
*(p+1) = *p;
}//插入位置及以后的元素右移
*q = e; //插入e
++L.length; //表长增1
printf("output after insert\n");
for(j=0;j<L.length;j++)
{
printf("%d ",L.elem[j]);
}
printf("\n");
return OK;
}
int main(void)
{
SqList L;
int result;
InitList_Sq(L); //构造一个空顺序表;
ListPrint_Sq(L,10); //输入顺序表元素;
ListInsert_Sq(L, 5, 0) ;//在第i个元素前插入元素
LocateElem_Sq(L, 5, compare); //查找匹配元素
return 0;
}