题目地址:http://pat.zju.edu.cn/contests/pat-a-practise/1074
题目意思比较容易理解,
有几个需要注意的点:
1,如果不能整除,最后几个不用反转。
2,输入中可能有不在链表中的点。
我的解法就是以空间换时间的方法,具体代码如下:
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
//ifstream in("1074.txt");
//#define cin in
typedef struct listNode
{
int key;
int addr;
}listNode;
int nextAddr[100005];
int Key[100005];
vector<listNode> a;
int main()
{
int begin,N,k;
cin >> begin >> N >>k;
int i;
for(i = 0;i<N;i++)
{
int address;
cin >> address;
cin >> Key[address] >> nextAddr[address];
}
while(begin != -1) //找出在一个链表上的元素。
{
listNode temp;
temp.key = Key[begin];
temp.addr = begin;
begin = nextAddr[begin];
a.push_back(temp);
}
int num = a.size() / k; //此处必须这样用,不能用N
vector<listNode>::iterator iter = a.begin();
for(i = 0;i<num;i++)
{
int start = i*k;
int end = (i+1)*k;
reverse(iter+start,iter+end); //反转函数
}
for(i = 0;i < a.size()-1;i++)
printf("%05d %d %05d\n",a[i].addr,a[i].key,a[i+1].addr);
printf("%05d %d -1\n",a[i].addr,a[i].key);
return 0;
}