码迷,mamicode.com
首页 > 其他好文 > 详细

2.1将线性表La和Lb合并成一个线性表

时间:2015-06-05 21:03:00      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

typedef int Status ;
typedef int ElemType;
#define OK 1
#define ERROR 0

#define LISTSIZE 10
#define ADDSIZE 2
typedef struct 
{
    ElemType *elem;
    int length;
    int listsize;
}SqList;

Status InitList(SqList *L)
{
    (*L).elem=malloc(LISTSIZE*sizeof(ElemType));
    if(!(*L).elem)
        exit(OVERFLOW);
    (*L).length=0;
    (*L).listsize=LISTSIZE;
    return OK;
}
Status GetElem(SqList L,int i,ElemType *e)
{
    if(i<1||i>L.length)
        return ERROR;
    *e=*(L.elem+i-1);
    return OK;
}
Status ListInsert(SqList *L,int i,ElemType e)
{
    ElemType *newbase,*p,*q;
    if(i<1||i>(*L).length+1)
        return ERROR;
    if((*L).length>=(*L).listsize)
    {
        newbase=(ElemType*)realloc((*L).elem,((*L).length+ADDSIZE)*sizeof(ElemType));
        if(!newbase)
            exit(OVERFLOW);
        (*L).elem=newbase;
        (*L).listsize+=ADDSIZE;
    }
    p=(*L).elem+i-1;
    q=(*L).elem+(*L).length-1;
    while(p<=q)
    {
        *(q+1)=*q;
        --q;
    }
    *p=e;
    ++(*L).length;
    return OK;
}
int ListLength(SqList L)
{
    return L.length;
}
Status LocateElem(SqList L,ElemType e,Status (*compare)(ElemType ,ElemType))
{
    int i=1;
    ElemType *p,*q;
    p=L.elem;
    q=L.elem+L.length-1;
    while(p<=q&&!compare(*p,e))
    {
        ++p;
        ++i;
    }
    if(i<=L.length)   
        return i;
    else
        return 0;
}
Status ListTraverse(SqList L,void(*visit)(ElemType))
{
    ElemType *p=L.elem;
    int i=1;
    while(i<=L.length)
    {
        visit(*p);
        ++p;
        ++i;
    }
    printf("\n");
    return OK;
}
Status equal(ElemType c1,ElemType c2)
{
    if(c1==c2)
        return 1;
    else
        return 0;
}
void Union(SqList *La,SqList Lb)
{
    ElemType e;
    int i,La_len,Lb_len;
    La_len=ListLength(*La);
    Lb_len=ListLength(Lb);
    for(i=1;i<=Lb_len;i++)
    {
        GetElem(Lb,i,&e);
        if(!LocateElem(*La,e,equal))
            ListInsert(La,++La_len,e);
    }
}
void print(ElemType c)
{
    printf("%d ",c);
}

void main()
{
    SqList La,Lb;
    int j;
    InitList(&La);
    for(j=1;j<=5;j++)
        ListInsert(&La,j,j);
    printf("La=");
    ListTraverse(La,print);
    InitList(&Lb);
    for(j=1;j<=5;j++)
        ListInsert(&Lb,j,2*j);
    printf("Lb=");
    ListTraverse(Lb,print);
    Union(&La,Lb);
    printf("new La=");
    ListTraverse(La,print);
}

程序运行如下:

技术分享

2.1将线性表La和Lb合并成一个线性表

标签:

原文地址:http://www.cnblogs.com/moya-com/p/4555434.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!