【PAT甲级】1074. Reversing Linked List (25)

直接用一个矩阵order存储节点地址,再这个矩阵上进行翻转,不知道算不算投机取巧

#include 
#include 
using namespace std;

struct Node {
    int e;
    int next;
};
Node list[100000];
void swap(int *a, int i, int j);

int main() {

    int start, len, k;
    cin >> start >> len >> k;

    for (int i = 0; i < len; i++) {
        int add, data, next;
        cin >> add >> data >> next;
        list[add].e = data;
        list[add].next = next;
    }
    int *order = new int[len];
    int p = 0;
    for (int i = start; i != -1; i = list[i].next) {
        order[p++] = i;
    }

    for (int i = 0; i + k - 1 < p; i += k) {
        for (int j = i; j <= (2 * i + k - 1)/2; j++) {
            swap(order, j, 2 * i + k - 1 - j);//注意这里多加一个i
        }
    }
    for (int i = 0; i < p - 1; i++) {
        list[order[i]].next = order[i + 1];
    }
    start = order[0];
    list[order[p - 1]].next = -1;

    int i;
    for (i = start; list[i].next != -1; i = list[i].next) {
        printf("%05d %d %05d\n", i, list[i].e, list[i].next);
    }
    printf("%05d %d %d\n", i, list[i].e, list[i].next);

    return 0;
}
void swap(int *a, int i, int j) {
    int tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;
    return;
}

你可能感兴趣的:(PAT)