1003: 顺序表(3)

1003: 顺序表(3)

Description

​ 请在上题SortList类的基础上添加成员函数Merge,实现两个有序表的合并。部分代码已经给出,请勿改动。注意:合并算法效率要求为O(m+n),不能借助排序算法实现。

//有序表类
template <class T>
class SortList
{
public:
    SortList() { length = 0; }
    ~SortList() {}
    void Insert(T x); // 有序表的插入,使序列仍有序
    void DispList(); // 输出表
    /*成员函数Merge实现两个有序表的合并,使序列仍有序,
       将A表和B表合并到当前类中,要求:A表,B表的元素保持不变*/
    void Merge(SortList<T> &A, SortList<T> &B);
private:
    T data[MaxSize]; // 存储元素
    int length; // 顺序表实际长度
};

// 构造有序表A:函数声明
template <class T>
void CreateSort(SortList<T> &A);
int main()
{
    SortList<int> A, B, C;
    // 生成一个有序表A
    CreateSort(A);
    // 生成一个有序表B
    CreateSort(B);
    try
    {
        C.Merge(A, B); // 合并A,B表为C表
    }
    catch (const char *wrong)
    {
        cout << wrong; // 如失败提示失败信息
    }
    A.DispList();
    B.DispList();
    C.DispList(); // 显示合并后的结果
    return 0;
}

// 构造有序表A:函数定义
template <class T>
void CreateSort(SortList<T> &A)
{
    int i, n;
    T x;
    cin >> n;
    for (i = 1; i <= n; i++)
    {
        cin >> x;
        try
        {
            A.Insert(x);
        }
        catch (char *wrong)
        {
            cout << wrong << endl;
        }
    }
}

Input

数据输入格式:第一个为所创建表的元素个数,之后是各个元素值,例如,下例输入,两个表的元素个数分别为5,6。

5 4 24 2 42 3
6 78 36 34 24 64 43

Output

Sample Input

5 4 24 2 42 3
6 78 36 34 24 64 43

Sample Output

The length:5
The elements:
2 3 4 24 42 
The length:6
The elements:
24 34 36 43 64 78 
The length:11
The elements:
2 3 4 24 24 34 36 42 43 64 78 
posted @ 2023-06-06 16:07  杨与S8  阅读(17)  评论(0编辑  收藏  举报