PAT A 1074 Reversing Linked List(25点)
2549 ワード
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:
where
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:
Sample Output:
コード:
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
コード:
#include
#include
using namespace std;
const int MAXV = 100010;
struct Node{
int address;
int data;
int next;
int order;
Node(){
order = 100011;
}
}node[MAXV];
bool cmp(Node a, Node b){
return a.order < b.order;
}
int main(){
int address, n, k;
scanf("%d %d %d", &address, &n, &k);
for(int i = 0; i < n; i++){
int adr, data, next;
scanf("%d %d %d", &adr, &data, &next);
node[adr].address = adr;
node[adr].data = data;
node[adr].next = next;
}
int tempaddress = address;
int count = 0; //
for(int j = 0; j < n; j++){
node[tempaddress].order = count++;
tempaddress = node[tempaddress].next;
if(tempaddress == -1) break;
}
sort(node, node + MAXV, cmp);
int total_reverse = count; //
int time_reverse = 0; //
while(total_reverse / k >0){
reverse(node + time_reverse * k, node + (time_reverse + 1) * k);
time_reverse++;
total_reverse -= k;
}
for(int t = 0; t < count; t++){
if(t == count-1) printf("%05d %d -1
", node[t].address, node[t].data);
else printf("%05d %d %05d
", node[t].address, node[t].data, node[t+1].address);
}
return 0;
}