线性表的合并

1.有序:

顺序表的合并:

typedef struct
{
    ElementType *elem;
    int length;
    int listsize;
}Sqlist;
/*La、Lb均为递增序列*/
void mergeList(Sqlist La, Sqlist Lb, Sqlist &Lc) {
    Lc.listsize = La.length + Lb.length;
    ElementType *pa,*pb,*pc,*pa_last,*pb_last;
    pa = La.elem;
    pb = Lb.elem;
    pa_last = pa + La.length - 1;
    pb_last = pb + Lb.length - 1;
    pc = Lc.elem = (ElementType *)malloc(sizeof(ElementType) * Lc.listsize);
    while(pa <= pa_last && pb <= pb_last){
        if(*pa >= *pb)
            *pc++ = *pb++;
        else
            *pc++ = *pa++;
    }
    while(pa <= pa_last) {
        *pc++ = *pa++;    
    }
    while(pb <= pb_last) {
        *pc++ = *pb++;
    }    
}
View Code

链表的合并:

typedef struct LNode
{
    ElementType data;
    struct LNode *next;
} *LinkList;
/*La和Lb两个升序链表最终合并成Lc链表(均带头节点)*/
void mergeList(LinkList &La,LinkList &Lb,LinkList &Lc){
    LinkList pa,pb,pc;
    pa = La->next;
    pb = Lb->next;
    pc = Lc = La;//Lc始终指向La链表的头节点
    while(pa && pb){
        if(pa->data <= pb->data) {
            pc->next = pa;
            pc = pa;
            pa = pa->next;    
        } else {
            pc->next = pb;
            pc = pb;
            pb = pb->next;
        }
    }
    pc->next = pa?pa:pb;//根据pa的null与否判断pc->next的值
    free(Lb);//除Lb的头节点外其他节点都将串成Lc链
}
View Code

两种方式时间复杂度均为O(n),但空间复杂度,前者由于需要重新分配空间存放Lc,因而更大。

 

2.无序:

求无序线性表La和Lb对应的集合A、B的并集AUB

/*La、Lb为无序列表求,求两表的并集*/
void unionL(List &La,List Lb) {
    int e;
    La_len = ListLength(La);
    Lb_len = ListLength(Lb);
    for(int i = Lb_len;i > 0;i--) {
        getElem(Lb,i,e);
        if(!LocateElem(La,e,equal)) {
            InsertL(La,++La_len,e);
        }
    }
}
View Code

该算法时间复杂度为O(La_length * Lb_length)。因为线性表无序,因而每从Lb中取个元素出来,都需要用LocateElem()在La中遍历一次。

posted @ 2016-05-09 16:49  Gabyler  阅读(709)  评论(0编辑  收藏  举报