数据结构中三表合一的实现

来源:互联网 发布:hello kitty主题软件 编辑:程序博客网 时间:2024/05/01 13:19

任务描述:La表的数据(3,5,8,11) Lb表的数据是(2,6,8,9,11,15,20)将La中的数据和Lb的数据按顺序依次插入到Lc中 但是要为Lc至少初始化一个数据 否则就插不进去 不知道怎么改 而且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的指针elemif(!L.elem)exit(0);//如果没有分配成功 那么存储失败L.length = 0;//长度为0L.listsize = LIST_INIT_SIZE;//初始容量是100return 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 true;}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+1if(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 true;}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 true; } int main() { IntNode La; IntNode Lb; IntNode Lc; IntList(La); IntList(Lb); IntList(Lc); InsertList(Lc,1); InsertList(La,4); InsertList(Lb,7); int i =1; int j =1; int k =0;     ElemType e = GetElem(La,1);while(i<=La.length&&j<=Lb.length){ElemType e1 = GetElem(La,i);ElemType e2 = GetElem(Lb,j);if(e1<=e2){ListInsert(Lc,++k,e1);++i;}else{ListInsert(Lc,++k,e2);++j;}}while(i<=La.length){ElemType e3 = GetElem(La,i++);ListInsert(Lc,++k,e3);}while(j<=Lb.length){ElemType e4 = GetElem(Lb,j++);ListInsert(Lc,++k,e4);}cout<<display(Lc,11)<<endl; cout<<endl; return 0;  }



原创粉丝点击