1074 Reversing Linked List (25 分)
Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K=3, then you must output 3→2→1→6→5→4; if K=4, you must output 4→3→2→1→5→6.
Input Specification:
Each input file contains one test case. For each case, the first line contains the address of the first node, a positive N (≤105) which is the total number of nodes, and a positive K (≤N) which is the length of the sublist to be reversed. The address of a node is a 5-digit nonnegative integer, and NULL is represented by -1.
Then N lines follow, each describes a node in the format:
Address Data Next
where Address
is the position of the node, Data
is an integer, and Next
is the position of the next node.
Output Specification:
For each case, output the resulting ordered linked list. Each node occupies a line, and is printed in the same format as in the input.
Sample Input:
00100 6 4
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
Sample Output:
00000 4 33218
33218 3 12309
12309 2 00100
00100 1 99999
99999 5 68237
68237 6 -1
/**
本题题意 :
给定一条链表
给定 k值 (需要反转的链表结点 eg: k = 3 表示 每3个结点反转一次, 没有三个结点时,就不需要反转)
本题思路:
1.链表题是存在无效结点的 (用next地址找到一条存在的路径 并将存在路径
的结点放入b数组中),因此最后输出时用b数组的长度输出
2. 运用 #include<algorithm>库中的reverse函数进行结点反转
**/
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int maxsize = 1e5 + 5;
struct Node{
int ad, next, data;
}a[maxsize];
vector<Node> b;
int main(){
int start, n, k;
scanf("%d%d%d", &start, &n, &k);
for(int i = 1; i <= n; i++){ //i是从1开始出发
int ad, data, next;
scanf("%d%d%d", &ad, &data, &next);
a[ad].ad = ad;
a[ad].data = data;
a[ad].next = next;
}
while(start != -1){ //2行解决的东西 就不要用 9行 好好思考一下。。。
b.push_back(a[start]);
start = a[start].next;
}
// while(a[start].next != -1){
// sum++;
// b[sum].data = a[start].data;
// b[sum].ad = a[start].ad;
// start = a[start].next;
// }
// sum++;
// b[sum].ad = a[start].ad;
// b[sum].data = a[start].data;
//
for(int i = k; i <= b.size(); i += k){ // 当存在 部分区间 < k(需要交换的区间)就不用交换,不用单独处理, i += k 如果有这样的区间会大于b的长度
reverse(b.begin() + i - k, b.begin() + i); //必须加头算法头文件
}
for(int i = 0; i < b.size(); i++){
printf("%05d %d ", b[i].ad, b[i].data);
if(i != b.size() - 1)
printf("%05d\n", b[i + 1].ad);
else
printf("-1\n");
}
return 0;
}