Given a constant k and a singly linked list L, you is 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 the one test case. The first line contains the address of the first node, a positive N (<=) which are the total number O F nodes, and a positive K (<=n) which are 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
The where Address is the position of the node, Data are 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 was 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
#include <cstdio> using namespace std;
#include <vector> const int max=100000+10;
int Node[max],next[max],previous[max];
int main () {int head,n,k;
scanf ("%d%d%d", &head,&n,&k);
int address,data,next_address;
for (int i=0;i<n;i++) {scanf ("%d%d%d", &address,&data,&next_address);
if (address!=-1) {node[address]=data;
next[address]=next_address;
} if (Address==head) previous[address]=-1;
if (next_address!=-1) previous[next_address]=address;
} vector<int> Index;
int cnt=0;//The number of nodes in the list for (int i=head;i!=-1;i=next[i]) {index.push_back (i);
printf ("previous=%d\n", Previous[i]);
cnt++;
} int round=cnt/k;
int m=k-1;
int last=-1;
while (m<cnt) {int i=m;
for (i;i>m-k+1;i--) {printf ("%05d%d%05d\n", Index[i],node[index[i]],previous[index[i]]); } if (m==cnt-1) printf ("%05d%d%d\n ", index[i],node[index[i]],-1);
else if (m+k>=cnt) printf ("%05d%d%05d\n", index[i],node[index[i]],index[m+1]);
else printf ("%05d%d%05d\n", index[i],node[index[i]],index[m+k]);
M+=k;
} for (int i=m-k+1;i<cnt;i++) {if (i!=cnt-1) printf ("%05d%d%05d\n", Index[i],node[index[i]],next[index[i]]);
else printf ("%05d%d%d\n", index[i],node[index[i]],-1);
} return 0; }