顺序表[A+B->C]

/*----代码段@映雪------*/
/*采用顺序表存储,改成数组也行*/

int MergeList(SeqList &A,SeqList &B,SeqList &C)
{
    int i=1,j=1,k=1;
    int e1,e2;
    while(i<=A.length && j<=B.length)
    {
        e1=GetElem(A,i);
        e2=GetElem(B,j);
        if(e1<e2)
        {
            InsertList(C,k,e1);
            i++;
            k++;
        }
        else if(e1==e2)/*如果两数相同,任取一个皆可*/
        {
            InsertList(C,k,e1);
            i++;/*两指针都前移一位*/
            j++;
            k++;
        }
        else 
        {
            InsertList(C,k,e2);
            j++;
            k++;
        }
    };
    while(i<=A.length)
    {
        e1=GetElem(A,i);
        InsertList(C,k,e1);
        i++;
        k++;
    };
    while(j<=B.length)
    {
        e2=GetElem(B,j);
        InsertList(C,k,e2);
        j++;
        k++;
    };
    C.length=A.length+B.length;
    return 0;
}

除此之外,并集的这个思路还可以求两个集合的相同元素,例,A={1,3,5,7},B={2,3,7},求两数组的相同元素

//完整代码 @映雪

#include <iostream>
using namespace std;
int main()
{
    int i=0,j=0;
    int b[]={3,5,7,8,20,45}; 
    int a[]={1,2,3,4,5,6,7,40,45};
    while(i<sizeof(b)/sizeof(int) && j<sizeof(a)/sizeof(int))
    {
        if(a[j]<b[i])
        {
            ++j;
        }
        else if(a[j]==b[i])
        {
            cout<<a[j]<<" ";
            ++j;
            ++i;
        }
        else
        {
            ++i;
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/tinaluo/p/5249195.html