资源简介
c语言实现线性表创建,插入,删除及合并的源代码。
代码片段和文件信息
#include
#include
#include
#include
#define OK 1
#define ERROR 0
#define OVERFLOW 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int ElemType;
using namespace std;
typedef struct
{
int *elem;
int length;
int listsize;
} SqList;
int InitList_Sq (SqList* L)
{
(*L).elem=(int *)malloc(LIST_INIT_SIZE*sizeof(int));
if(!(*L).elem)
exit(OVERFLOW);
(*L).length=0;
(*L).listsize=LIST_INIT_SIZE;
return OK;
}
int CreateList_Sq ( SqList L )
{
int i;
printf(“请输入数据: \n“);
for(i=0;i scanf(“%d“&L.elem[i]);
return OK;
}
int InsertList_Sq ( SqList *L int i ElemType e ){
ElemType *newbase *p *q;
if(i<1 || i>L->length+1)
return ERROR;
if(L->length >= L->listsize)
{
newbase = (ElemType *)realloc(L->elem (L->listsize+LISTINCREMENT)*sizeof(ElemType) );
if(!newbase)
printf(“类存分配失败“);
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;
}
int ListDelete_Sq( SqList &L int i int &e )
{
int *p*q;
if ( i<1 || i >L.length )
return ERROR;
p=&(L.elem[i-1]);
e=*p;
q=L.elem+L.length-1;
for ( ++p; p<=q; ++p )
*(p-1)=*p;
--L.length;
cout<<“被删除的结点为:“< return OK;
}
void PrintList_Sq ( SqList L )
{
int z=0;
while(z < L.length)
{
printf(“%3d“ L.elem[z]);
z++;
}
printf(“\n“);
}
void MergeList_Sq(SqList La SqList Lb SqList *Lc) {
ElemType *pa *pb *pc *pa_last *pb_last;
pa = La.elem;
pb = Lb.elem;
Lc->listsize = Lc->length = La.length + Lb.length;
Lc->elem = (ElemType*) malloc (Lc->listsize * sizeof(ElemType));
pc = Lc->elem;
if(!Lc->elem) exit(OVERFLOW);
pa_last = La.elem + La.length - 1;
pb_last = Lb.elem + Lb.length - 1;
while( pa <= pa_last && pb <= pb_last) {
if(*pa <= *pb) *pc++ = *pa++;
else *pc++ = *pb++;
}
while(pa <= pa_last) *pc++ = *pa++;
while(pb <= pb_last) *pc++ = *pb++;
}
void INSERTION_SORT(SqList *A)
{
int i j key;
for(j = 1; j != A->length; j++) {
key = A->elem[j];
i = j - 1;
while( i >= 0 && A->elem[i] > key ) {
A->elem[i+1] = A->elem[i];
--i;
}
评论
共有 条评论