您的位置:首页 > 理论基础 > 数据结构算法

数据结构中La表的数据合并到Lb表中

2013-09-11 19:44 477 查看
实验描述:La表中的数据为(3,5,8,11) Lb 表中的数据为(2,6,8,9,11,15,20) 将La表中的数据而不存在Lb表的数据插入到Lb表中,从而实现并集操作。

出现的问题:最后实现的线性表的末端始终有个0 我认为是display返回的状态代码 不知道怎么删除 求大神指教。

#include <iostream>
//包含文件
using namespace std;

#define LIST_INIT_SIZE 100
//初始化分配量

#define LISTINCREMENT 10
//存储空间的分配增量

typedef int status;
//存储结构的类型定义 返回函数的状态结果代码
typedef int ElemType;
//数据元素/結点的表示 这个是用户自定义的数据类型 用于结点
typedef struct{

ElemType *elem;//结点的储存空间首地址

int length;//当前长度

int listsize;//当前的分配的存储容量 (以sizeof (ElemType)为单位)
}IntNode; //相当于在java中定义了一个叫IntNode的结点类

status IntList(IntNode &L)
{//这个函数实现的是构建一个空线性表 在这之前我们要为其分配100个ElemType大小的

L.elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
//分配100个ElemType大小的存储空间,并把地址分配给指向ElemType的指针elem

if(!L.elem)

exit(0);//如果没有分配成功 那么存储失败

L.length = 0;//长度为0

L.listsize = LIST_INIT_SIZE;//初始容量是100

return true;

}

status InsertList(IntNode &L,int n)
{

cout<<"请输入数据"<<endl;

for(int i =0;i<n;i++)
{
cin>>L.elem[i];

++L.length;

if(L.length>=L.listsize)
{

ElemType * newbase;

newbase = (ElemType *)realloc(L.elem,

(L.listsize+LISTINCREMENT)*sizeof(ElemType));

if(!newbase)

exit(0);

L.elem= newbase;

L.length+=LISTINCREMENT;
//这段代码的意思是 当线性表的长度小于最大分配的空间时

//你就要重新分配出110的分配空间 并将指针赋给newbase

}
}

return L.length;

}

status ListLength(IntNode &L)
{

int answer;

for(int i =0;i<L.length;i++)
{
answer++;
}

return L.length;
}

status  ListInsert(IntNode &L,int i,ElemType e)
{//在i的位置之前插入e元素 并使L的长度增加
//有了前置条件 i必须是不超出线性表范围的    1<=i<=L.length+1

if(i>L.length||i<0)

return false;

if(L.length>=L.listsize)
{

ElemType * newbase;

newbase = (ElemType *)realloc(L.elem,

(L.listsize+LISTINCREMENT)*sizeof(ElemType));

if(!newbase)

exit(0);

L.elem= newbase;

L.length+=LISTINCREMENT;
//这段代码的意思是 当线性表的长度小于最大分配的空间时

//你就要重新分配出110的分配空间 并将指针赋给newbase

}

ElemType *p =&(L.elem[i-1]);//指定的位置

for(ElemType *q = &(L.elem[L.length-1]);q>=p;--q)

{
*(q+1)=*(q);//插入位置及之后的元素右移
}
*p =e;

++L.length;

return 1;

}

status GetElem(IntNode &L,int i) {

ElemType *p =  & (L.elem[i-1]);

ElemType e = *p;

return e;

}

status LocateElem(IntNode &L,ElemType e)
{
ElemType *p =&(L.elem[0]);//首位置

for(ElemType *q = &(L.elem[L.length-1]);p<=q;p++)
{
if(e==*p)

return true;

}

return false;
}

status display(IntNode &L,int n){

for ( int i = 0; i <=n ; i ++)
{
cout << L.elem[i]<< "  ";
}

return 0;

}

int main()
{

IntNode La;

IntNode Lb;

IntList(Lb);
IntList(La);

InsertList(La,4);

InsertList(Lb,7);

for(int i=1 ;i <=4;i++)
{
ElemType e = GetElem(La,i);

if(!LocateElem(Lb,e))
{

ListInsert(Lb,++Lb.length,e);

--Lb.length;

cout<<endl;

}
}

cout<<display(Lb,8);

cout<<endl;

return 0;

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: