PAT (Advanced Level) 1074. Reversing Linked List (25)

简单题。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;

const int maxn=100000+10;

struct Node
{
    char Address[10];
    char Data[100];
    char Next[10];
} node[maxn],tmp[maxn],pri[maxn];

int n,k;
map<string,int>m;
char StAdd[10];

void Copy(int a,int b)
{
    strcpy(tmp[a].Address,node[b].Address);
    strcpy(tmp[a].Data,node[b].Data);
    strcpy(tmp[a].Next,node[b].Next);
}

int main()
{
    scanf("%s%d%d",StAdd,&n,&k);
    m.clear();
    for(int i=0; i<n; i++)
    {
        scanf("%s%s%s",node[i].Address,node[i].Data,node[i].Next);
        m[node[i].Address]=i;
    }

    int now=m[StAdd];
    int kk=0;
    while(1)
    {
        Copy(kk,now);
        if(strcmp("-1",node[now].Next)==0) break;
        kk++;
        now=m[node[now].Next];
    }

    now=0; int c=0;
    while(now<kk+1)
    {
        if(now+k-1<kk+1)
        {
            for(int i=now+k-1; i>=now; i--)
            {
                strcpy(pri[c].Address,tmp[i].Address);
                strcpy(pri[c].Data,tmp[i].Data);
                c++;
            }
            now=now+k;
        }
        else
        {
            for(int i=now; i<kk+1; i++)
            {
                strcpy(pri[c].Address,tmp[i].Address);
                strcpy(pri[c].Data,tmp[i].Data);
                c++;
            }
            now=kk+1;
        }
    }

    for(int i=0; i<kk+1; i++)
    {
        printf("%s %s ",pri[i].Address,pri[i].Data);
        if(i<kk+1-1) printf("%s
",pri[i+1].Address);
        else printf("-1
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zufezzt/p/5634261.html