7-1 线性表A,B顺序存储合并

有两张非递增有序的线性表A,B,采用顺序存储结构,两张表合并用c表存,要求C为非递减有序的,然后删除C表中值相同的多余元素。元素类型为整型

#include<iostream>
#define Max 100
using namespace std;

typedef struct  
{
    int *elem;
 
   int length;
}SqList;

SqList input(SqList &L)
{
    L.elem = new int[Max];
    int a;
    int i = 0;
    cin>>a;
    while(a != -1)
    {
        if(L.elem[i-1] != a) //非递增有序的线性表A,删除C表中值相同的多余元素
          L.elem[i++] = a;
        cin>>a;
    }
    L.length = i;
    return L;
}
void add( SqList &a ,SqList &b , SqList &c)
{
    c.elem = new int [Max];
    c.length = 0;
    
    int i = a.length - 1;
    int j = b.length - 1;
    int k = 0;
    
    while(i>=0 && j>=0)
    {
        if(a.elem[i ] >  b.elem[j ])
        {
            c.elem[k++] = b.elem[j--];
        }
        else if(a.elem[i ] ==  b.elem[j ])
        {
             c.elem[k++] = b.elem[j--];
             i--;
        }
        else
        {
             c.elem[k++] = a.elem[i--];
        }
    }
    while(i>=0)
    {
        c.elem[k++] = a.elem[i--];
    }
     while(j>=0)
    {
        c.elem[k++] = b.elem[j--];
    }
    c.length = k;
    
}
void show(SqList &c)
{
    int  k = 1;
    cout<<c.elem[0];
    while( k < c.length )
    {
        cout<<","<<c.elem[ k++ ];
    }
    
}
int main()
{
    SqList A,B,C;
    input(A);
    input(B);
    add(A,B,C);
    show(C);
    return 0;
}

 

posted @ 2022-10-24 23:51  旺旺大菠萝  阅读(79)  评论(0编辑  收藏  举报