Http://www.patest.cn/contests/mooc-ds/02-1
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 the ' the ' of the ' the ' of the ' the ' the ' the ' the ' the ' the ' the ' Positive N (<=) which is the total number O F 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 is the position of the node, the Data is a 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 are 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 <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
#define MAXN 100001
typedef struct{
int addr;
int data;
int next;
} Node;
Node NODES[MAXN];
vector<node> list;
int main () {
int firstadd, n, K;
scanf ("%d%d%d", &firstadd, &n, &k);
while (n--) {
Node nn;
scanf ("%d%d%d", &nn.addr, &nn.data, &nn.next);
NODES[NN.ADDR] = nn;
}
int address = Firstadd;
while (address!=-1) {
list.push_back (nodes[address]);
address = Nodes[address].next;
}
int length = List.size ();
int round = length/k;
for (int i = 1; I <= round ++i) {
int start = (i-1) *k;
int end = I*k;
Reverse (List.begin () + Start, list.begin () + end);
}
for (int i = 0; i < length-1 ++i) {
printf ("%05d%d%05d\n", List[i].addr, List[i].data, list[i+1].addr);
printf ("%05d%d%d\n", List[length-1].addr, List[length-1].data,-1);
return 0;
}