线性表的应用:将所有在线性表Lb中但不在线性表La中的元素插入线性表La
#include<iostream>
#include<stdio.h>
#include <malloc.h>
using namespace std;
#define MaxSize 50
typedef char ElemType;
typedef struct
{
ElemType elem[MaxSize]; //存放顺序表中的元素
int length; //存放顺序表的长度
} SqList;
void InitList(SqList *&L) //初始化线性表,构造一个空的线性表,并将长度设置为0
{
L=(SqList *)malloc(sizeof(SqList));
L->length=0;
}
int ListLength(SqList *L) //求线性表的长度
{
return(L->length);
}
int GetElem(SqList *L,int i,ElemType &e)//求线性表中某个数据元素的值
{
if (i<1 || i>L->length)
return 0;
e=L->elem[i-1];
return 1;
}
int LocateElem(SqList *L, ElemType e)//按元素查找,找到与该元素值相同的元素并返回其序号
{
int i=0;
while (i<L->length && L->elem[i]!=e) i++;
if (i>=L->length)
return 0;
else
return i+1;
}
int ListInsert(SqList *L,int i,ElemType e)//插入数据元素,在第i个位置上插入新元素,使后面的元素依次后移,并是长度加1;
{
int j;
if (i<1 || i>L->length+1)
return 0;
i--; /*将顺序表位序转化为elem下标*/
for (j=L->length;j>i;j--) /*将elem[i]及后面元素后移一个位置*/
L->elem[j]=L->elem[j-1];
L->elem[i]=e;
L->length++; /*顺序表长度增1*/
return 1;
}
int ListEmpty(SqList *L) //判断线性表是否为空 即看其长度是否为0
{
return(L->length==0);
}
void DispList(SqList *L) //输出线性表
{
int i;
if (ListEmpty(L)) return;
for (i=0;i<L->length;i++)
printf("%c",L->elem[i]);
printf("\n");
}
void Union(SqList *La,SqList *Lb){
ElemType e;
int La_len;
int Lb_len;
La_len=ListLength(La);
Lb_len=ListLength(Lb);
for(int i=1;i<=Lb_len;i++){
GetElem(Lb,i,e);
if(!LocateElem(La,e)) ListInsert(La,++La_len,e);
}
}
void main()
{
SqList *La;
SqList *Lb;
ElemType e;
int La_len;
int Lb_len;
int i;
printf("(1)初始化顺序表L\n");
InitList(La);
InitList(Lb);
printf("输入La");
for(i=0;i<5;i++)
{ cin>>e;
ListInsert(La,i,e);}
printf("输入Lb");
for(i=0;i<5;i++)
{ cin>>e;
ListInsert(Lb,i,e);}
/*ListInsert(La,1,'a');
ListInsert(La,2,'b');
ListInsert(La,3,'c');
ListInsert(La,4,'d');
ListInsert(La,5,'e');
printf("(2)依次采用尾插法插入元素\n");
ListInsert(Lb,1,'a');
ListInsert(Lb,2,'b');
ListInsert(Lb,3,'c');
ListInsert(Lb,4,'d');
ListInsert(Lb,5,'5');*/
printf("输出线性表L:");
DispList(La);
DispList(Lb);
Union(La,Lb);
/*La_len=ListLength(La);
Lb_len=ListLength(Lb);
for(int i=1;i<=Lb_len;i++){
GetElem(Lb,i,e);
if(!LocateElem(La,e)) ListInsert(La,++La_len,e);
}*/
printf("输出插入完成后的线性表:");
DispList(La);
}
代码参考:https://blog.csdn.net/ciganxian/article/details/27549653
还没有评论,来说两句吧...