#include"pre.h"
#include<stdlib.h>
#include<stdio.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef char ElemType;
typedef struct{
ElemType *elem;
int length;
int listsize;
}SqList;
Status InitList_Sq(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;
}
void CreateList_Sq(SqList*L, int n)
{
int i;
fflush(stdin);
while(n>L->listsize)
L->listsize += LIST_INIT_SIZE;
for(i=1;i<=n;i++)
scanf("%c",L->elem+i-1);
L->length = n;
}
Status GetElement_Sq(SqList*L,int i,ElemType*e)
{
if(i<1||i>L->length)return ERROR;
*e = L->elem[i-1];
return OK;
}
Status ListInsert_Sq(SqList*L,int i,ElemType e)
{
ElemType*p,*last,*q;
if(i<1||i>L->length+1)return ERROR;
if(L->length>=L->listsize)
{
ElemType*newBase = (ElemType*)realloc(L->elem,(L->listsize+LISTINCREMENT)*sizeof(ElemType));
if(!newBase)exit(OVERFLOW);
L->elem = newBase;
L->listsize += LISTINCREMENT;
}
p = L->elem + i - 1;
last = L->elem + L->length - 1;
for(q = last;q>=p;q--)
*(q+1) = *q;
*p = e;
L->length++;
return OK;
}
Status ListDelete_Sq(SqList*L,int i,ElemType*e)
{
ElemType*p,*q;
if(i<1 || i>L->length)return ERROR;
*e = L->elem[i-1];
p = L->elem + i - 1;
for(q=p+1;q<=L->elem+L->length-1;q++)
*(q-1) = *q;
L->length--;
return OK;
}
void PrintList_Sq(SqList*L)
{
int i=0;
for(i=0;i<L->length;i++)
printf("%c",L->elem[i]);
}
int LocateElem_Sq(SqList*L,ElemType e,Status(*compare)(ElemType,ElemType))
{
ElemType*p = L->elem;
int i = 1;
while(!(*compare)(e,*p++)&&i<=L->length)i++;
if(i<=L->length)return i;
else return 0;
}
void MergeList_Sq(SqList La,SqList Lb,SqList*Lc)
{
ElemType*pa=La.elem,*pb=Lb.elem,*pc;
ElemType*lasta=La.elem+La.length-1,*lastb=Lb.elem+Lb.length-1;
int la = La.length,lb = Lb.length;
Lc->listsize = Lc->length = la + lb;
pc = Lc->elem = (ElemType*)malloc(Lc->listsize*sizeof(ElemType));
while(pa<=lasta&&pb<=lastb)
{
if(*pa<=*pb)
*pc++ = *pa++;
else
*pc++ = *pb++;
}
while(pa<=lasta)*pc++ = *pa++;
while(pb<=lastb)*pc++ = *pb++;
}
int IsEqual(ElemType a,ElemType b)
{
if(a == b)return 1;
else return 0;
}
int main()
{
SqList La,Lb,Lc;
int i;
InitList_Sq(&La);
CreateList_Sq(&La,5);
PrintList_Sq(&La);
/*InitList_Sq(&Lb);
CreateList_Sq(&Lb,4);
PrintList_Sq(&Lb);
MergeList_Sq(La,Lb,&Lc);
printf("\n");
PrintList_Sq(&Lc);*/
i = LocateElem_Sq(&La,'c',IsEqual);
printf("i=%d\n",i);
return 0;
}
顺序表的实现
最新推荐文章于 2024-08-19 12:55:05 发布