1. 程式人生 > >C++順序表應用3:元素位置互換之移位演算法(好好看著函式名!!)要不然就會 undefined reference to `build_table(Table&, int, int)'

C++順序表應用3:元素位置互換之移位演算法(好好看著函式名!!)要不然就會 undefined reference to `build_table(Table&, int, int)'

順序表應用3:元素位置互換之移位演算法

Time Limit: 1000 ms Memory Limit: 570 KiB

Problem Description

一個長度為len(1<=len<=1000000)的順序表,資料元素的型別為整型,將該表分成兩半,前一半有m個元素,後一半有len-m個元素(1<=m<=len),藉助元素移位的方式,設計一個空間複雜度為O(1)的演算法,改變原來的順序表,把順序表中原來在前的m個元素放到表的後段,後len-m個元素放到表的前段。 注意:先將順序表元素調整為符合要求的內容後,再做輸出,輸出過程只能用一個迴圈語句實現,不能分成兩個部分。

Input

 第一行輸入整數n,代表下面有n行輸入; 之後輸入n行,每行先輸入整數len與整數m(分別代表本表的元素總數與前半表的元素個數),之後輸入len個整數,代表對應順序表的每個元素。

Output

 輸出有n行,為每個順序表前m個元素與後(len-m)個元素交換後的結果

Sample Input

2
10 3 1 2 3 4 5 6 7 8 9 10
5 3 10 30 20 50 80

Sample Output

4 5 6 7 8 9 10 1 2 3
50 80 10 30 20

Hint

注意:先將順序表元素調整為符合要求的內容後,再做輸出,輸出過程只能在一次迴圈中完成,不能分成兩個部分輸出。

#include<iostream>
#include<cstdlib>
using namespace std;

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

void build_table(Table &a, int len, int m);
void rebuild_table(Table &a);
void swap_num(Table &a, int l, int r);
void pri_num(Table &a);
void delete_memory(Table &a);

int main(void)
{
    int len, m, T;
    Table test;

    cin >> T;

    while(T--)
    {
        cin >> len >> m;
        build_table(test, len, m);
        rebuild_table(test);
        pri_num(test);
        delete_memory(test);
    }

    return 0;
}

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

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

void rebuild_table(Table &a)
{
    swap_num(a, 1, a.m);
    swap_num(a, a.m + 1, a.len);
    swap_num(a, 1, a.len);
}

void swap_num(Table &a, int l, int r)
{
    int mid = (l + r) / 2, t;

    for(int i = l; i <= mid; i++)
    {
        t = a.num[i], a.num[i] = a.num[l + r - i], a.num[r + l - i] = t;
    }
}

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

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