weixin_39626495 于 2017.09.16 14:43 提问

#include
#include
#define LIST_INT_SIZE 100
#define LISTINCREMENT 10

typedef struct
{
int *elem;
int length;
int listsize;
}SqList;//结构体

int InitList_Sq(SqList &L)
{
L.elem = (int*)malloc(LIST_INT_SIZE * sizeof(int));
if (!L.elem)
{
printf("ERROR\n");
return 0;
}
L.length = 0;
L.listsize = LIST_INT_SIZE;
return 1;
}//初始化

int ListDelete_Sq(SqList &L, int i)
{
int *p;
int *q;
if ((i < 1) || (i > L.length))
return 0;
p = &(L.elem[i - 1]);
q = L.elem + L.length - 1;
for (++p; p <= q; ++p)
{
*(p - 1) = *p;
}
--L.length;
return 1;
}//删除操作

int ListInsert_Sq(SqList &L, int i, int e)
{
int newbase;
int *q;
int *p;
if ((i < 1) || (i > L.length))
return 0;
if (L.length >= L.listsize)
{
newbase = (int
)realloc(L.elem, (L.listsize + LISTINCREMENT) * sizeof(int));
if (!newbase)
{
printf("ERROR\n");
return 0;
}
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
q = &(L.elem[i]);
for (p = &(L.elem[L.length - 1]); p >= q; --p)//从后向前，每个数的位置移动；
{
*(p + 1) = *p;
}
*q = e;
L.length++;
return 1;
}//插入操作

void MergeList_Sq(SqList LA, SqList LB, SqList &LC)
{
int *pa;
int *pa_last = LA.elem + LA.length - 1;
int *pb;
int *pb_last = LB.elem + LB.length - 1;
int *pc;
pa = LA.elem;
pb = LB.elem;
LC.listsize = LC.length = LA.length + LB.length;
pc = LC.elem = (int *)malloc(LC.listsize * sizeof(int));
if (!LC.elem)
printf("ERROR\n");
while (pa <= pa_last&&pb <= pb_last)
{
if (*pa < *pb)
*pc++ = *pa++;
else if (*pa > *pb)
*pc++ = *pb++;
else if (*pa == *pb)
{
*pc = *pa;
pa++;
pb++;
pc++;
LC.length--;
}
}
while (pa<=pa_last)
{
*pc ++ = *pa++;
}

``````while (pb <= pb_last)
{
*pc++ = *pb++;
}
``````

}//合并

void show(SqList &L, int length)
{
int *r;
int n=1;
for (r = L.elem; n <= length; r++)
{
printf("%d ", *r);
n++;
}
printf("\n");
}//展示数列中的值;

int main()
{
int num;
int loc;
int a[5] = { 1,3,5,7,9 };
int b[7] = { 2,4,5,8,10,13,15};
SqList LA, LB,LC;
InitList_Sq(LA);
InitList_Sq(LB);
InitList_Sq(LC);
LA.elem = a;
LA.length = 5;
LB.elem = b;
LB.length = 7;
show(LA, LA.length);
show(LB, LB.length);

``````printf("请输入你要删除第几个数：");
scanf("%d", &loc);
ListDelete_Sq(LA, loc);
show(LA, LA.length);
printf("请输入你要插入数的位置：");
scanf("%d", &loc);
printf("请输入你要插入的数：");
scanf("%d", &num);
ListInsert_Sq(LB, loc,num);
show(LB, LB.length);

MergeList_Sq(LA, LB, LC);
show(LC, LC.length);
``````

}

1个回答

caozhy      2017.09.17 09:18