算法列表 |
顺序表初始化 |
在顺序表中插入数据 |
删除顺序表中的数据 |
合并两个升序顺序表 |
#include <stdio.h>
#include <iostream>
#define MAXLENGTH 50
#define ElemType int
typedef struct {
ElemType* val;
int length;
}SqList;
/* 初始化顺序表 */
bool initList(SqList &q)
{
q.val = (ElemType *)malloc(sizeof(ElemType)*MAXLENGTH);
if (q.val == NULL)
return false;
q.length = 0;
return true;
}
/* 在顺序表中插入数据*/
bool ListInsert_sq(SqList &L, int i, ElemType x) {
if (i<1 || i>L.length + 1)
return false;
if (L.length+1 > MAXLENGTH)
return false;
ElemType * q = &(L.val[i - 1]);
for (ElemType * p = &(L.val[L.length - 1]);p >= q;--p)
*(p+1) = *p;
*q = x;
L.length++;
return true;
}
/* 删除顺序表中第i个结点 */
bool ListDelSq(SqList &L, int i, ElemType &e)
{
if (i<1 || i>L.length)
return false;
ElemType *q = &(L.val[i - 1]);
e = *q;
while (q != &(L.val[L.length - 1]))
{
*q = *(q + 1);
q++;
}
L.length--;
return true;
}
/*
合并两个升序顺序表,结果仍然按升序排列并储存在Lc中
*/
bool MergeListSq(SqList La, SqList Lb, SqList &Lc)
{
Lc.val = (ElemType *)malloc(sizeof(int)*(La.length + Lb.length));
if (Lc.val == NULL)
return false;
ElemType *Pa = La.val;
ElemType *Pb = Lb.val;
ElemType *PaLast = &La.val[La.length-1];
ElemType *PbLast = &Lb.val[Lb.length-1];
ElemType *Pc = Lc.val;
while (Pa <= PaLast && Pb <= PbLast)
{
if (*Pa < *Pb)
{
*Pc++ = *Pa++;
}
else
{
*Pc++ = *Pb++;
}
}
while(Pa <= PaLast)*Pc++ = *Pa++;
while (Pb <= PbLast)*Pc++ = *Pb++;
Lc.length = La.length + Lb.length;
return true;
}
int main()
{
SqList La;
SqList Lb;
SqList Lc;
initList(La);
initList(Lb);
int j = 1;
int k = 1;
for (int i = 0;i < 20;i++)
{
if (i % 2)
ListInsert_sq(La, j++, i);
else
ListInsert_sq(Lb, k++, i);
}
MergeListSq(La, Lb, Lc);
for (int i = 0;i < La.length;i++)
printf("%d ", La.val[i]);
printf("\n");
for (int i = 0;i < Lb.length;i++)
printf("%d ", Lb.val[i]);
printf("\n");
for (int i = 0;i < Lc.length;i++)
printf("%d ", Lc.val[i]);
getchar();
return 0;
}