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 (≤) which is the total number of nodes, and a positive K (≤) 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
Good heavens! A list write one day
#include <the iostream> #include <stdio.h> the using namespace STD; struct the Node { int the Num; int the Next; // next address } List [ 100001 ]; // address as the beginning of 100,000 void Print ( int n-) { IF (n-== - . 1 ) { COUT << - . 1 ; return ; } int T = 10000 ; the while (T) { COUT << n-/ T; n-=n%t; t=t/10; } } int main() { int fir,N,K; scanf("%d %d %d",&fir,&N,&K); //cin>>fir>>N>>K; List[100000].Next=fir; for(int i=0;i<N;++i) { int t1,t,t2; //cin>>t1>>t>>t2; scanf("%d %d %d",&t1,&t,&t2); List[t1].Num i;= List[t1].Next=t2; } int P1=List[fir].Next,P2=List[fir].Next,P3=fir,P4=100000; while(1) {//cout<<"P4="<<P4<<" P3="<<P3<<" P2="<<P2<<" P1="<<P1<<endl; int flag=1; for(int i=1;i<K;i++) { if(P1!=-1) { P1=List[P1].Next; List[P2].Next=P3; P3=P2; P2=P1; } else { flag=0; break; } //cout<<"aaP4="<<P4<<" P3="<<P3<<" P2="<<P2<<" P1="<<P1<<endl; } if(flag) { int y=List[P4].Next; List[P4].Next=P3; P3=y; //cout<<"P3="<<P3<<endl; //for(int j=1;j<K;++j) P3=List[P3].Next; List[P3].Next=Pl; // restoring P4 = P3; P3 = P2; IF (P2 == - . 1 ) BREAK ; // just ended Pl = List [Pl] .NEXT; P2 = List [P2] .NEXT; // COUT << "P4 =" << << P4 "P3 =" P3 << << "P2 =" P2 << << "Pl =" << endl << Pl; } the else // end has a tail withdrawal operation ( debug: multi-step back, ah ah A) { the while (P3 =! List [P4] .NEXT) !!! // { // Pl = P2; P2=P3; P3=List[P3].Next; List[P2].Next=P1; P1=P2; } break; } } //cout<<endl; int P=100000; while(1) { P=List[P].Next; print(P); cout<<" "<<List[P].Num<<" "; print(List[P].Next); cout<<endl; if(List[P].Next==-1) break; } return 0; }