pat乙级 1025 反转链表 [测试点5超时]
给定一个常数K以及一个单链表L,请编写程序将L中每K个结点反转。例如:给定L为1→2→3→4→5→6,K为3,则输出应该为3→2→1→6→5→4;如果K为4,则输出应该为4→3→2→1→5→6,即最后不到K个元素不反转。
输入格式:
每个输入包含 1 个测试用例。每个测试用例第 1 行给出第 1 个结点的地址、结点总个数正整数 N (≤105)、以及正整数 K (≤N),即要求反转的子链结点的个数。结点的地址是 5 位非负整数,NULL 地址用 −1 表示。
接下来有 N 行,每行格式为:
Address Data Next
其中 Address 是结点地址,Data 是该结点保存的整数数据,Next 是下一结点的地址。
输出格式:
对每个测试用例,顺序输出反转后的链表,其上每个结点占一行,格式与输入相同。
输入样例1:
00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
输出样例1:
00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1
总结:
1
按着首地址和下一结点地址将链表串起来
2
每K个结点反着输出结点信息,next地址也会发生变化
3
计算反转多少次 t=len/reverse
4
反转数据
5
当不等于最后一个结点时:输出
当前元素地址 当前元素数据 下个元素地址
//反转
for(int j=0;j<t;j++){
reverse(res.begin() + j*re, res.begin() + j*re + re);
}
//输出
for (int i = 0; i < len; i++){
if (i != len - 1){
cout << res[i].address << " " << res[i].data <<" "<< res[i + 1].address << endl;
}
else
{
cout << res[i].address << " " << res[i].data << " " << "-1" << endl;
}
}
代码:
#include <iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
struct node{
string address;
int data;
string next;
node(string add, int da, string ne){
address = add;
data = da;
next = ne;
}
};
int main(){
string first;
int n;
int re;
vector<node> v;
cin >> first >> n >> re;
for (int i = 0; i < n; i++){
string add;
int da;
string ne;
cin >> add >> da >> ne;
node no = node(add, da, ne);
v.push_back(no);
}
vector<node> res;
string fi = first;
if (first != "-1"){
for (int i = 0; i < n; i++){
if (fi == "-1"){
break;
}
if (v[i].address == fi){
res.push_back(v[i]);
fi = v[i].next;
i = -1;
}
}
int len = res.size();
int t = len / re;
for (int j = 0; j < t; j++){
reverse(res.begin() + j*re, res.begin() + j*re + re);
}
for (int i = 0; i < len; i++){
if (i != len - 1){
cout << res[i].address << " " << res[i].data <<" "<< res[i + 1].address << endl;
}
else
{
cout << res[i].address << " " << res[i].data << " " << "-1" << endl;
}
}
}
system("pause");
return 0;
}