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 (≤10^5 ) 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
结尾无空行
思路:
数据的顺序是打乱的,需要根据节点地址给它们连起来;由题目得知,节点的地址是5位数,则可以将节点的地址作为结构体数组的下表,再使用另外的数组保存地址的对应顺序,即可达到按地址连接的目的。
序列的逆转难点在于,每k长度的区间都要进行逆转,不足k区间长度的剩余元素不进行逆转,所以何时退出逆转程序很重要;还有进行逆转操作时,要从区间的一左一右同时交换位置;
代码:
#include <stdio.h>
#define Maxsize 100005
struct node{
int data;
int next_add; //下一个节点的地址
}list[Maxsize];
int cnt[Maxsize]; //记录每个节点排好顺序后的地址,与下标一一对应
int main(){
int first_add, n, k;
scanf("%d %d %d", &first_add, &n, &k);
int now_add;
for(int i=0; i<n; i++){
scanf("%d", &now_add);
//节点的对应地址作为下标
scanf("%d %d", &list[now_add].data, &list[now_add].next_add);
}
int sum = 0; //记录有效的节点个数
now_add = first_add; //从第一个节点地址开始,到地址为-1结束
while (now_add != -1){
cnt[sum++] = now_add;
now_add = list[now_add].next_add; //移动到此节点连接的下一个节点位置
}
添加一段测试输出的代码,进行检验
for(int i=0; i<n-1; i++)
printf("%05d %d %05d\n", cnt[i], list[cnt[i]].data, list[cnt[i]].next_add);
printf("%05d %d %d", cnt[n-1], list[cnt[n-1]].data, list[cnt[n-1]].next_add);
此时我们输入样例,可以看到最后输出的结果是可以排列好的
下面的是最重要的部分,序列逆转
// 每个k长度的区间内元素都需要逆转,步长为k 即i+=k
for(int i=0; i<sum; i+=k){
if((sum-i) < k) break;
//区间内元素一首一尾调换位置,循环k/2次
for(int j=0; j<k/2; j++){
int tmp = cnt[i+j];
cnt[i+j] = cnt[i+k-j-1];
cnt[i+k-j-1] = tmp;
}
}
最后的输出格式很重要,一定要这样写,否则测试点无法全部通过
for (int i = 0; i < sum; i++){
if(i == sum-1) printf("%05d %d -1\n", cnt[i], list[cnt[i]].data);
else printf("%05d %d %05d\n", cnt[i], list[cnt[i]].data, cnt[i+1]);
}