PAT 1074
输入
00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
  输出
00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1
  #include <cstdio>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
const int maxn=100010;
//定义静态链表 
struct Node{
    int address,data,next;
    //结点在链表上的序号,无效结点记为maxn 
    int order;
}node[maxn];
bool cmp(Node a,Node b)
{
    //按order从小到大排序 
    return a.order<b.order;
}
int main()
{
    for(int i=0;i<maxn;i++)
    {
        node[i].order=maxn;
    }
    int begin,n,k,address;
    //起始地址,结点个数,步长 
    scanf("%d%d%d",&begin,&n,&k);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&address);
        scanf("%d%d",&node[address].data,&node[address].next);
        node[address].address = address;
    }
    //count 计数有效结点的数目 
    int p= begin,count=0;
    //遍历链表找出单链表中的所有有效结点 
    while(p!=-1)
    {
        //结点在单链表中的序号 
        node[p].order=count++;
        //下一个结点 
        p=node[p].next;
    }
    //按单链表从头到尾顺序排列
    sort(node,node+maxn,cmp);
    //有效结点为前count个结点,为了下面书写方便,因此把count赋给n
    n=count;
    //单链表已经形成,下面是按题目要求的输出
    //枚举完整的n/k 块 
    for(int i=0;i<n/k;i++) 
     {
        //第i块倒着输出 
        for(int j =(i+1)*k-1;j>i*k;j--   )
        {
            printf("%05d %d %05d\n",node[j].address,node[j].data,node[j-1].address);;
        }
        //下面是每一块的最后一个结点的next地址的处理
        printf("%05d %d ",node[i*k].address,node[i*k].data); 
        //如果不是最后一块,就指向下一块的最后一个结点 
        if(i<n/k-1)
        {
            printf("%05d\n",node[(i*2)*k-1 ].address);
        }
        else    //是最后一块时 
        {
            if(n%k==0) 
            {
                printf("-1\n"); //恰好是最后一个结点,输出-1 
            }
            else    //剩下不完整的块按原先的顺序输出 
            {
                printf("%05d\n",node[ (i+1)*k ].address);
                for( int i=n/k*k;i<n;i++ )
                {
                    printf("%05d %d ",node[i].address,node[i].data);
                    if(i<n-1)
                    {
                        printf("%05d\n",node[i+1].address);
                    }
                    else
                    {
                        printf("-1\n");
                    }
                }
            }
        }
     }
    return 0;
} 

京公网安备 11010502036488号