#include<stdio.h>
#include<stdlib.h>
#define Status int
#define INIT_SIZE 20
#define LISTINCREMENT 10
#define N 10
//数据类型
typedef struct
{
int number;
}ElemType;
//顺序表存储结构
typedef struct
{
ElemType *pstu;
int Length;
int Listsize;
}SqList;
//初始化顺序表
Status InitList(SqList &L)
{
if(!L.pstu)
{
L.pstu = (ElemType *)malloc(sizeof(ElemType) * INIT_SIZE);
if(!L.pstu)
return 0;
L.Length = 0;
L.Listsize = INIT_SIZE;
return 1;
}
return 0;
}
//插入操作
Status InsertList(SqList &L, int i,ElemType e)
{
if(i<=0 || i>L.Length+1)
return 0;
if(L.Length >= L.Listsize)
{
ElemType *q;
q = (ElemType *)realloc(L.pstu,sizeof(ElemType) * (LISTINCREMENT + INIT_SIZE));
if(!q)
return 0;
L.Listsize = INIT_SIZE + LISTINCREMENT;
L.pstu = q;
}
ElemType *m,*n;
m = L.pstu+i-1;
for(n=L.pstu+L.Length-1;n>=m;n--)
{
*(n+1) = *n;
}
*m = e;
L.Length++; //长度要更新
return 1;
}
//删除操作
Status DeleteList(SqList &L,int i,ElemType &e)
{
if(i<=0 || i>L.Length+1)
return 0;
ElemType *m,*n;
m = L.pstu+i-1;
e = *m;
for(n=m;n<L.pstu+L.Length;n++)
{
*n = *(n+1);
}
L.Length--;
return 1;
}
//判断是否在表中
Status GetElem(SqList L,int i)
{
ElemType *m;
if(i<=0 || i>L.Length)
return 0;
m = L.pstu+i-1;
return (*m).number;
}
//找到位置(逻辑位置)
Status LocateList(SqList L,ElemType e)
{
int i=0;
ElemType *m;
for(m=L.pstu;m<=L.pstu+L.Length-1;m++)
{
i++;
if((*m).number == e.number) //*****
{
return i;
}
}
return 0;
}
//销毁表
Status DestoryList(SqList &L)
{
if(!L.pstu)
return 0;
free(L.pstu);
L.pstu = NULL;
L.Length = 0;
L.Listsize = INIT_SIZE;
return 1;
}
//合并有序线性表
Status MergeList(SqList La, SqList Lb, SqList &Lc)
{
ElemType *p1 = La.pstu;
ElemType *p2 = Lb.pstu;
ElemType *p3 = Lc.pstu;
Lc.Listsize = Lc.Length = La.Length + Lb.Length;
while(p1 < La.pstu+La.Length && p2 < Lb.pstu+Lb.Length)
{
if((*p1).number <= (*p2).number)
{
*p3++ = *p1++;
}
else
{
*p3++ = *p2++;
}
}
while(p1<La.pstu+La.Length)
{
*p3++ = *p1++;
}
while(p2<Lb.pstu+Lb.Length)
{
*p3++ = *p2++;
}
return 1;
}
//主函数
void main()
{
SqList La,Lb,Lc;
ElemType num;
La.pstu = NULL;
Lb.pstu = NULL;
Lc.pstu = NULL;
InitList(La);
printf("插入顺序表a\n");
for(int i=1;i<=3;i++)
{
scanf("%d",&num.number);
InsertList(La,i,num);
}
InitList(Lb);
printf("插入顺序表b\n");
for(i=1;i<=3;i++)
{
scanf("%d",&num.number);
InsertList(Lb,i,num);
}
InitList(Lc);
printf("顺序表c合并\n");
MergeList(La,Lb,Lc);
for(i=1;i<=6;i++)
{
printf("The NO.%d is %d\n",i,GetElem(Lc,i));
}
}
【数据结构-C语言实现】合并有序线性表
最新推荐文章于 2022-12-01 18:33:06 发布