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个节点反转,然后输出,剩余节点原序输出。
思路:地址没有超出10的五次方使用静态链表处理,利用order作为特殊标志位链表进行排序,输出时将链表划分成n/k个模块依次进行输出,但每当到达每个模块最后一个节点时需要进行讨论:如果该模块<n/k-1,那么下一个节点就是(i+2)乘k减1,否则需要讨论后面有没有节点:如果没有输出-1,如果还有那么下一个节点就是(i+1)乘k,然后依次输出。
AC
#include<stdio.h>
#include<algorithm>
using namespace std;
const int maxn=100010;
struct node{
int address,next,data;
int order;
}nodes[maxn];
bool cmp(node a,node b){
return a.order<b.order;
}
int main(){
for(int i=0;i<maxn;i++){
nodes[i].order=maxn;
}
int st,n,k,address;
scanf("%d%d%d",&st,&n,&k);
for(int i=0;i<n;i++){
scanf("%d",&address);
scanf("%d%d",&nodes[address].data,&nodes[address].next);
nodes[address].address=address;
}
int count=0,p=st;
while(p!=-1){
nodes[p].order=count++;
p=nodes[p].next;
}
sort(nodes,nodes+maxn,cmp);
n=count;
for(int i=0;i<n/k;i++){//划分块
for(int j=i*k+k-1;j>i*k;j--){//倒序输出
printf("%05d %d %05d\n",nodes[j].address,nodes[j].data,nodes[j-1].address);
}
printf("%05d %d ",nodes[i*k].address,nodes[i*k].data);//第i块的最后一个
if(i<n/k-1){//确定下一个节点
printf("%05d\n",nodes[(i+2)*k-1].address);
}else{//最后一个模块
if(n%k==0){//是否有剩余节点
printf("-1\n");
}else{
printf("%05d\n",nodes[(i+1)*k].address);
for(int m=(i+1)*k;m<n;m++){//输出剩余节点
if(m==n-1){
printf("%05d %d -1\n",nodes[m].address,nodes[m].data);
}else{
printf("%05d %d %05d\n",nodes[m].address,nodes[m].data,nodes[m].next);
}
}
}
}
}
}