7-2 Block Reversing (25分)
Given a singly linked list L. Let us consider every K nodes as a block (if there are less than K nodes at the end of the list, the rest of the nodes are still considered as a block). Your job is to reverse all the blocks in L. For example, given Las 1→2→3→4→5→6→7→8 and K as 3, your output must be 7→8→4→5→6→1→2→3.
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 size of a block. 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 8 3
71120 7 88666
00000 4 99999
00100 1 12309
68237 6 71120
33218 3 00000
99999 5 68237
88666 8 -1
12309 2 33218
Sample Output:
71120 7 88666
88666 8 00000
00000 4 99999
99999 5 68237
68237 6 00100
00100 1 12309
12309 2 33218
33218 3 -1
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
struct NODE{
int add,data,next;
}List[1000009];
struct Block{
vector< struct NODE > v;
}B;
int main(void){
int N,K,fadd,add,data,next;
cin>>fadd>>N>>K;
for( int i=0 ; i<N; i++ ){
cin>>add>>data>>next;
List[add].add =add;
List[add].data =data;
List[add].next =next;
}
int cnt=0;
B.v.resize( K +1 );
stack< struct Block > s;
for( int i=fadd; i!=-1; i=List[i].next ){
B.v[++cnt] = List[i];
if( cnt == K ){
s.push( B );
cnt =0;
}
}
int flag =0;
if( cnt != 0 )
for( int i=1;i<=cnt;i++){
if(!flag ){
printf("%05d %d",B.v[i].add,B.v[i].data);
flag =1;
}
else printf(" %05d\n%05d %d",B.v[i].add,B.v[i].add,B.v[i].data);
}
while( !s.empty() ){
B = s.top();
s.pop();
for( int i=1;i<B.v.size();i++){
if( !flag ){
printf("%05d %d",B.v[i].add,B.v[i].data);
flag =1;
}
else printf(" %05d\n%05d %d",B.v[i].add,B.v[i].add,B.v[i].data);
}
}
printf(" -1\n");
}