PAT甲1074. Reversing Linked List (25)

  1. 注意题目是每k个倒置,即k=2时,123456要倒置成214365,题目给的例子根本没有代表性嘛,浪费了好多时间检查。
  2. 用一个临时的节点数组按顺序存放节点,在该数组上进行倒置操作,方便很多。
#include <cstdio>
#include <cstdlib>
#include <string.h>
#include <cmath>
#include <algorithm>
#include <string>
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
using namespace std;

const int maxn=100010;

struct Node
{
    int c;
    int next;
    int now;
    bool flag;
    int pre;
    Node()
    {
        flag=false;
    }
}node[maxn];

Node temp[maxn];

void reverse(int begin,int k)
{
    for(int i=0;i<k/2;i++)
    {
        swap(temp[begin+i],temp[begin+k-i-1]);
    }
}

int main()  
{   
    int begin,N,K;
    scanf("%d%d%d",&begin,&N,&K);
    int now;
    for(int i=0;i<N;i++)
    {
        scanf("%d",&now);
        scanf("%d%d",&node[now].c,&node[now].next);
        node[now].now=now;
    }
    int order=0;
    for(int j=begin;j!=-1;j=node[j].next)
    {
        node[j].flag=true;
        temp[order]=node[j];
        order++;
    }
    int group=order/K;
    for(int i=0;i<group;i++)
    {
        reverse(K*i,K);
    }
    for(int i=0;i<order;i++)
    {
        if(i!=order-1)
        {
            temp[i].next=temp[i+1].now;
        }
        else
        {
            temp[i].next=-1;
        }
    }
    for(int i=0;i<order;i++)
    {
        if(i!=order-1)
        {
            printf("%05d %d %05d\n",temp[i].now,temp[i].c,temp[i].next);
        }
        else
        {
            printf("%05d %d -1\n",temp[i].now,temp[i].c);
        }
    }
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yhy489275918/article/details/80102439