1. 程式人生 > >順序表應用5:有序順序表歸併(函式的傳遞)

順序表應用5:有序順序表歸併(函式的傳遞)

順序表應用5:有序順序表歸併

Time Limit: 100 ms Memory Limit: 880 KiB

Problem Description

已知順序表A與B是兩個有序的順序表,其中存放的資料元素皆為普通整型,將A與B表歸併為C表,要求C表包含了A、B表裡所有元素,並且C表仍然保持有序。

Input

 輸入分為三行:
第一行輸入m、n(1<=m,n<=10000)的值,即為表A、B的元素個數;
第二行輸入m個有序的整數,即為表A的每一個元素;
第三行輸入n個有序的整數,即為表B的每一個元素;

Output

 輸出為一行,即將表A、B合併為表C後,依次輸出表C所存放的元素。

Sample Input

5 3
1 3 5 6 9
2 4 10

Sample Output

1 2 3 4 5 6 9 10
#include<iostream>
#include<cstdlib>
using namespace std;

struct Table
{
    int *num;
    int len;
};

void build_table(Table &a, int len);
void union_table(Table &a, Table &b, Table &c);
void pri_num(Table &c);
void delete_memory(Table &a);

int main(void)
{
    int m, n;
    Table a, b, c;

    cin >> m >> n;

    build_table(a, m);
    build_table(b, n);
    union_table(a, b, c);
    pri_num(c);
    delete_memory(a);
    delete_memory(b);
    delete_memory(c);

    return 0;
}

void build_table(Table &a, int len)
{
    a.len = len;
    a.num = new int [len + 4];

    for(int i = 1; i <= len; i++)
    {
        cin >> a.num[i];
    }
}

void union_table(Table &a, Table &b, Table &c)
{
    c.len = a.len + b.len;
    c.num = new int [c.len + 4];

    int i = 1, j = 1, k = 0;
    while(i <= a.len && j <= b.len)
    {
        if(a.num[i] >= b.num[j])
        {
            c.num[++k] = b.num[j];
            j++;
        }

        else
        {
            c.num[++k] = a.num[i];
            i++;
        }
    }

    while(i <= a.len)
    {
        c.num[++k] = a.num[i];
        i++;
    }

    while(j <= a.len)
    {
        c.num[++k] = b.num[j];
        j++;
    }

}

void pri_num(Table &c)
{
    for(int i = 1; i <= c.len; i++)
    {
        cout << c.num[i];
        i == c.len ? cout << '\n' : cout << ' ';
    }
}

void delete_memory(Table &a)
{
    delete []a.num;
}